I have a form with an input that has a name an id.
When I try to get the value of the input by using document.getElementById, I get an error.
I can access the element by using the form name and the input name, but it makes the script a lot less flexible.
Any workarounds?
Here’s the code I have:
<form name='myform'>
<input name='n1' id='i1' value='stuff'>
</form>
<script>
var s=document.getElementById("i1").value;
alert(s);
</script>
I have the script in an external .js file and I want to make sure that if someone changes the name of the form, the script still works.
You code works just fine, look at this example
Just make sure that you call the script after the DOM is ready. Also make sure that there are no other elements with the same
id.