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?
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?
Share Improve this question edited Jun 23, 2009 at 15:40 Alex Rozanski 38k10 gold badges69 silver badges69 bronze badges asked Jun 23, 2009 at 15:35 Zeeshan RangZeeshan Rang 19.9k29 gold badges74 silver badges103 bronze badges6 Answers
Reset to default 3Looks 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>
You can use the following after you add an id attribute to input tag
document.getElementById('id').value
maybe document.forms.formxml.xmlname.value
You can also use:
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>