javascript - parent child checkbox selection -


<input type="checkbox" name="all[]" id="<?php echo $record_id;?>" value="<?php echo $record_id; ?>" onclick="childchecked(this, this.form.elements['prnt'])"> 

above code creates dynamic child checkboxes each row fetching data database

<input type="checkbox" name="all[]" id="<?php echo $record_id;?>" value="<?php echo $record_id; ?>" onclick="allchecked(this, this.form.elements['prnt'])"> 

and above parent checkbox

javascript code:

function checkall(){         var main_check=document.getelementbyid("check");         var all_check=document.getelementsbyname('all[]');         if(main_check.checked){             for(var i=0;i<all_check.length;i++){                 all_check[i].checked=true;             }         }else{             for(var i=0;i<all_check.length;i++){                 all_check[i].checked=false;             }         }     } function childchecked(child, prnt){     if (!child.length){ // if not array         prnt.checked = child.checked;         //alert(prnt.checked);         return;     }     (var i=0; i<child.length; i++){         if (!child[i].checked)     return; } prnt.checked = true; } 

above code parent child checkbox selection does: 1. checks/unchecks child checkboxes on checking/unchecking parent checkbox 2. unchecks parent checkbox if 1 of child checkbox unchecked

and problem is, checks parent checkbox if checked single child checkbox want parent checkbox checked if , if child checkboxes checked

your code can simplified:

var main_check = document.getelementbyid("check"); var all_check = document.getelementsbyname('all[]');  main_check.onchange = checkall;  (var = 0; < all_check.length; i++) {     all_check[i].onchange = childchanged; }  function checkall() {     (var = 0; < all_check.length; i++) {         all_check[i].checked = main_check.checked;     } }  function childchanged() {     if (!this.checked) {         main_check.checked = false;         return;     }      // check if main checkbox should checked     (var = 0; < all_check.length; i++) {         if (!all_check[i].checked) return;     }      main_check.checked = true; } 

and html:

<input type="checkbox" id="check" /> main  <ul>     <li><input type="checkbox" name="all[]" /></li>     <li><input type="checkbox" name="all[]" /></li>     <li><input type="checkbox" name="all[]" /></li>     <li><input type="checkbox" name="all[]" /></li> </ul> 

i got rid of inline event handlers.

demo: http://jsfiddle.net/txrnf/


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -