简体   繁体   中英

check and uncheck boxes in javascript

I have a script that checks and check all boxes in a form, my problem is that I only want it to affect only my checkboxes but it also affecting my radio buttons.

This is my javascript

    <script>

checked=false;
function checkedAll (frm1) {
    var aa= document.getElementById('frm1');
     if (checked == false)
          {
           checked = true
          }
        else
          {
          checked = false
          }
    for (var i =0; i < aa.elements.length; i++) 
    {
     aa.elements[i].checked = checked;
    }
      }
</script>

This is my html

<form id ="frm1">
<input type="checkbox" name="chk1">
<input type="radio" name="chk1">
<input type="checkbox" name="chk2">
<input type='checkbox' name='checkall' onclick='checkedAll(frm1);'>
</form>

I was wondering whether there was a way to check only the checkboxes not the radio button.

for (var i =0; i < aa.elements.length; i++) 
{
    if (aa.elements[i].type == "checkbox") {
        aa.elements[i].checked = checked;
    }
}

You can loop through the form elements and check for the "type" property. Alternately, you can use a javascript library like jQuery, which makes it easier to select elements of certain type.

var elLength = document.MyForm.elements.length;

for (i=0; i<elLength; i++)
{
    var type = MyForm.elements[i].type;
    if (type=="checkbox" && MyForm.elements[i].checked){
        alert("Form element in position " + i + " is of type checkbox and is checked.");
    }
    else if (type=="checkbox") {
        alert("Form element in position " + i + " is of type checkbox and is not checked.");
    }
    else {
    }
}

In jQuery it would be:

$("input[type='checkbox']).each(function(chk) {
    chk.checked = !chk.checked;
});

You can use jquery . use the html code below in your editor. it works correctly!

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.js">    </script>
</head>
    <form id="myform">  
       <input type="checkbox" />chk1  
       <input type="checkbox" />chk2<br/>    
       <input type="radio" />radio1<br/>       
       <a style="cursor:pointer" onclick="ch()">check/uncheck</a>
    </form>
</body></html>

and this script:

 <script>
    function ch(){
        $("form#myform input[type='checkbox']").each(function(chk) {
            this.checked = !this.checked;
        });        
    }
 </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM