Checkbox selection covers a wide range of topics

  • 2020-03-30 01:11:08
  • OfStack

1. Internet explorer works, firefox doesn't

IE version
 
<script type="text/javascript"> 

function checkALL(str)//Select fully controlled JS
{ 
var a=document.getElementsByName(str); 
var n=a.length; 

for(var i=0;i<n;i++) 

{ 

a[i].checked=window.event.srcElement.checked; 

} 

} 

</script> 

Firefox versions
 
<script type="text/javascript"> 

function checkALL(str)//Select fully controlled JS
{ 
var a=document.getElementsByName(str); 
var n=a.length; 
for(var i=0;i<n;i++){ 
a[i].checked=document.getElementById("all").checked; 
} 
} 

</script> 

Window.event can only run under IE, so js won't work in firefox. In the firefox version, you simply get the "id = all" checkbox selected state and assign each item to the "name = STR" checkbox group to keep the selection state synchronized.

2, the document. The getElementById () with the document. GetElementsByName ()

In the above section, js gets the state of the checkbox in two ways. In terms of names, they should be similar, one by id and the other by name. However, there is a difference between the two methods, if you do not pay attention to the use process, it is likely to feel can be mixed, which will cause trouble. At that time, I thought it was good to use a random one, but after changing the name, js code did not work, in fact, because I did not understand, resulting in the use of the wrong.

(1) document.getelementbyid () is to access a specific Element by id, because id is unique in a page, so this function returns an Element

(2) of the document. The getElementsByName () by name to access Elements, because in a page name is not the only, can the nuptial, so this function returns a set of Elements

It is precisely because one is an element and the other is an array that errors will occur if you don't pay attention when mixing, resulting in js running down. For example, I put a[I].checked= document.getelementbyid ("all").checked; To a [I]. Checked = document. GetElementsByName (" all "). Checked; Run, js doesn't work (because js error but not an error, so the feeling is not work), actually isn't recognition here, because use the wrong call, correct term is a [I]. Checked = document. GetElementsByName (" all ") [0]. Checked; After changing like this, the effect is the same. Since there is only one checkbox with "name=all" in our page, we use [0] to fetch the first element in the Elements, which is a[I].checked= document.getelementbyid ("all").checked; The element that you get.

Related articles: