What is the difference between these codes?

<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 the above code we use

alert(val[0].value);

alert(window.txtName.value);

these are two ways to get value from an object. What is the difference between both ways and which way is best.

+3
source share
3 answers
alert(window.txtName.value);

This is the wrong way that only works on IE. IE copies all named and IDd elements into properties windowand, therefore, also global variables that cause all kinds of problems. Do not rely on this.

The best way to do it like this:

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

assuming inputbeing in the first <form>on the page. You can also use the form name if it is:

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

and you can also reduce it:

alert(document.someform.txtName.value);

, .

:

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

, id='txt' , , name:

alert(document.getElementById('txt').value);
+9

, txtName name. .

, txtName shorthand, txtName, window.

, , , ; , , . , .

, id - document.getElementById('txt').value - , .

+2

This line of code recognizes the entire homepage ie total html

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

There may be an error below, because in the next line it adds textName to the window object.

alert(window.txtName.value);

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

0
source

Source: https://habr.com/ru/post/1747974/


All Articles