views:

143

answers:

3
<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.

A: 

This line of code find out whole dom i.e whole html page

var val = document.getElementsByName('txtName');
alert(val[0].value);

Following might be the error because by the following line it's add textName to the window object.

alert(window.txtName.value);

chck more about this : http://snook.ca/archives/javascript/global_variable

Pranay Rana
That's not correct. "window" is the "global variable scope" object when javascript is running in a browser. Any global variable is also a property of the "window" object.
Philippe Leybaert
+2  A: 

In the first method, you're finding all the elements that have a value of txtName for their name properties. From the result, you're fetching the first matched item.

In the second method, you rely on the browser to have made the element with the name txtName accessible via a shorthand property, txtName, on the window object.

As you can see, one is superfluous if you know there's always just one element; and the other is problematic if you don't know that there's always just one element. Also, in most browsers, the second method won't even work.

I wouldn't recommend any of those means of accessing an item, but rather access by id - document.getElementById('txt').value - when you know there's just one specific element that you want to access.

David Hedlund
+7  A: 
alert(window.txtName.value);

This is the Wrong Way, which only works on IE. IE copies all named and IDd elements into properties of window and hence also global variables, which causes all sorts of problems. Don't rely on this.

The better way of doing it like that is:

alert(document.forms[0].elements.txtName.value);

assuming that the input was in the first <form> on the page. You can also use a form name, if it has one:

alert(document.forms.someform.elements.txtName.value);

and it's also possible to shorten that:

alert(document.someform.txtName.value);

although I wouldn't recommend doing so as you stand a greater chance of clashes between names and properties.

This:

alert(document.getElementsByName('txtName')[0].value);

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-unique name attribute:

alert(document.getElementById('txt').value);
bobince
Thanks bob......
Karandeep Singh
@dhali: If this answer suits your needs, please tick the check mark, so we can see this question got answered good enough.
Marcel Korpel