I have an HTML page and and external JavaScript file. How do I access the value of an input
tag from the HTML page in JavaScript? My HTML is as follows:
<form name="formxml">
<input type="text" name="xmlname"/>
<input type="submit" value="Click me please" onclick="loadxml()"/>
</form>
In the Javascript file, I was trying:
var name = document.formxml.xmlname.value
but this gives an error of "document.formxml is undefined"
What should I do?
Looks like the external js can't find the form yet because it's parsed before the page is rendered? Not sure about it, but putting it in a function and calling the function on the page (when it's done loading) does work:
function foo () {
var name = document.formxml.xmlname.value;
alert(name);
}
and
<form action="" method="post" name="formxml">
<input type="text" name="xmlname" value="123" id="xmlname">
<input type="button" onclick="foo();">
</form>
将id属性添加到输入标签后,可以使用以下命令
document.getElementById('id').value
maybe document. forms .formxml.xmlname.value
您还可以使用:
var name = document.forms[0].xmlname.value; //where [0] means the first form on the page
var name = document.formxml.value; //Will not work in all browsers
var name = document.forms[0].xmlname.value; //safest if the form is the first on the page
var name = document.getElementById('inputId').value; //works in basically everything assuming the browser has DHTML (which is like everything).
The last one requires your input elem to have an id="inputId" added to it.
Also your code will work, assuming the form exists when the external js is loaded (which is why forms[0] will work here and formxml will not.
Try this
<script>
function yourfunction()
{
var x = document.getElementsByName("fieldname").value;
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.