Question

I want alert if check-box is not checked (- this is working )

and

Alert if ALL check-box is not checked ( need help in this )

CheckBox :

<input type="checkbox" value="1" id="data" name="data[]">
<input type="checkbox" value="2" id="data" name="data[]">
<input type="checkbox" value="3" id="data" name="data[]">

Button :

<input name=\"submitclose\" type=\"submit\"  value=\"Close\" id=\"submitclose\">

Below is my Jquery :

echo "<script>
jQuery(function($)  {
$(\"input[id='submitclose']\").click(function() {  

                var count_checked = $(\"[id='data']:checked\").length; 
                if (count_checked == 0)  {
                        alert(\"Please select a Packet(s) to Close.\");
                        return false;
                } else{     
                        return confirm(\"Are you sure you want to Close these Packet?\");
                }  
        });
}); 
</script>";
Was it helpful?

Solution

Try,

HTML:

<input type="checkbox" value="1" id="data1" name="data[]">
<input type="checkbox" value="2" id="data2" name="data[]">
<input type="checkbox" value="3" id="data3" name="data[]">

JS:

var allCheckBox = $("[id^='data']")
var count_checked = allCheckBox.filter(":checked").length; 
if (count_checked == 0)  {
    alert("All check boxes are not checked");
} else if(count_checked != allCheckBox.length) {
    alert("some of the check boxs are not checked");
} else{     
    return confirm("Are you sure you want to Close these Packet?");
}

OTHER TIPS

$(\"input[id='submitclose']\").click(function(){
    var count = 0;
    $('input#data').each(function(){   
    if ($(this).attr('checked') == true){
    count++  //if a checkbox is checked the variable count will be greater then 0.
    }
})
    if (count == 0){      //nothing is checked.
    alert("Please check at least one of the checkboxes");
}else{       //something is checked.
    //code to execute.
}

})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top