Javascript focus () and select () quirk

Im working on the form and getting null or not object errors in ie.

<form action="#" method="post" name="adv_search">

<input class="inputbox" type="text" name="keyword1" value="none" id="keyword1"/>
</form>

<script>
document.adv_search.keyword1.focus();
document.adv_search.keyword1.select();
</script>

//, whereas if I use

<script>
var key1 = document.getElementById('keyword1');
   key1.focus();
   key1.select();
</script>

//everything is fine

I would like to understand why. I would like it to work without id tag for input field

early


should not document.formname.fieldname.focus (); and document.formname.fieldname.select (); work?

+3
source share
2 answers

Your specific example works for me, but if I add another field with the same name:

<input type="text" name="keyword1" />
<input type="text" name="keyword1" />

Then it document.adv_search.keyword1.focus()will fail with the error you specified.

The reason is that:

document.adv_search.keyword1

is a shortcut for this syntax (which returns to DOM Level 0 and Netscape 2 days!):

document.forms.adv_search.elements.keyword1

(, , , : HTMLDocument HTMLFormElement, , . , document.forms form.elements. , IE "", , id="adv_search" , document.adv_search .)

, DOM Level 0 , , . , . , , , . focus() select() , ; - keyword1 [0].focus(), .

, , DOM 0 - - , ID, "DOM Level 1:

document.getElementById('keyword1').focus();

, ID, , ( script , , ), . ( name <form> .)

+9

, , getElementsByName.

:

<script>
   // retrieves array of objects with the name 'keyword1' 
   // and takes the first one
   var key1 = document.getElementsByName('keyword1')[0]; 
   key1.focus();
   key1.select();
</script>
+2

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


All Articles