<input type='text' id='txt' name='txtName' size='20' value='testing'/>
<script type="text/javascript" language='javascript'>
var val = document.getElementsByName('txtName');
alert(val[0].value);
alert(window.txtName.value);
</script>
In above code we are using
alert(val[0].value);
alert(window.txtName.value);
these two ways for getting value from object. What is the difference between both ways and which way is best.
This is the Wrong Way, which only works on IE. IE copies all named and IDd elements into properties of
windowand hence also global variables, which causes all sorts of problems. Don’t rely on this.The better way of doing it like that is:
assuming that the
inputwas in the first<form>on the page. You can also use a form name, if it has one:and it’s also possible to shorten that:
although I wouldn’t recommend doing so as you stand a greater chance of clashes between names and properties.
This:
is OK, but since you already have
id='txt'on the input it’s going to be simpler and faster to use that instead of relying on the non-uniquenameattribute: