How to check multiple checkboxes checked using jquery?

前端 未结 5 1786
别那么骄傲
别那么骄傲 2021-01-19 02:27

i am new to the jquery, it is quite interesting, but i am having a little problem, i am populating multiple checkboxes from database using foreach loop like this,



        
5条回答
  •  孤城傲影
    2021-01-19 03:24

    To find how many checkboxes are checked, you can use something like:

    var checkedNum = $('input[name="city[]"]:checked').length;
    if (!checkedNum) {
        // User didn't check any checkboxes
    }
    

    Since you're providing the same name attribute to all the checkboxes (from your PHP loop), you can use the selector input[name="city[]"] to target and find them all. But to find out how many specifically are checked, you can add the :checked selector. An alternative to this is using $('input[name="city[]"]').filter(":checked").

    Finally, !checkedNum will only pass if checkedNum is 0, since 0 is falsey. Any other number is truthy, and wouldn't satisfy the condition !checkedNum.


    References:

    • jQuery attribute equals selector: http://api.jquery.com/attribute-equals-selector/
    • :checked selector: http://api.jquery.com/checked-selector/
    • jQuery .length property: http://api.jquery.com/length/

提交回复
热议问题