views:

398

answers:

5

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?

+2  A: 

You can use the following after you add an id attribute to input tag

document.getElementById('id').value
Jonathan Mayhak
An additional ID is not necessary.
Gumbo
+2  A: 

maybe document.forms.formxml.xmlname.value

David
+1  A: 

You can also use:

var name = document.forms[0].xmlname.value; //where [0] means the first form on the page
karim79
+1  A: 
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.

i tried all three of these. none of them are working. Are these codes supposed to work for the external javascript too??
Zeeshan Rang
by external javascript are you refering to importing it from a file like <javascript src="someplace" type="text/javascript">? Whether you do it that way or just embedd the code in your html it is the same thing
+1  A: 

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>
MSpreij
thanks MSpreij. your solution works perfect for me.
Zeeshan Rang