Check if you have any checkbox checked and enable button

2

How to do in JQuery, a function that checks if there is a checkbox selected, if there is any one it enables the delete button, if there is more than 1 it places the text in the plural.

I made the following code:

DEMO JSFIDDLE

fiddler version 2.0 update

NOTE: I did the example below in pure javascript, but I would like it to be in JQUERY. And it still has some error that only enables when the last one is marked.

<script>
function verificaChecks() {
        var checados=0;
        var aChk = document.getElementsByName("chk_IDDel"); 
        for (var i=0;i<aChk.length;i++){ 
            if (aChk[i].checked == true){ 
                checados++;
                 document.getElementById('btn_Deletar').removeAttribute("disabled");
                if(checados >1)
                {
                    document.getElementById("btn_Deletar").value='Deletar registroS';
                }
            }  else {
                document.getElementById('btn_Deletar').setAttribute("disabled","disabled");

                 if(checados >1)
                {
                    document.getElementById("btn_Deletar").value='Deletar registroS';
                }
                else
                {
                    document.getElementById("btn_Deletar").value='Deletar registro';
                }

            }
        }
    } 
</script>

    <form>
        <input type="checkbox" name="chk_IDDel" id="chk_IDDel" value='1' onchange="verificaChecks()" />
            <br>
        <input type="checkbox" name="chk_IDDel" id="chk_IDDel" value='2' onchange="verificaChecks()" />
            <br>
        <input type="checkbox" name="chk_IDDel" id="chk_IDDel" value='3' onchange="verificaChecks()" />
            <br>
        <input type="checkbox" name="chk_IDDel" id="chk_IDDel" value='4' onchange="verificaChecks()" />
            <br><br>

    <input type="submit" value="deletar registro" id="btn_Deletar" class="btn btn-danger" disabled="true"  />
    </form>
    
asked by anonymous 14.07.2014 / 16:31

1 answer

4

Remove onchange="verificaChecks()" from inputs and do so with jQuery:

$(function(){
    $("[name='chk_IDDel']").change(function(){
        var countSelected = $("input[name=chk_IDDel]:checked").length;
        var $btnDeletar = $('#btn_Deletar');
        $btnDeletar.prop("disabled", countSelected == 0);
        $btnDeletar.val('Deletar registro' + (countSelected > 1 ? 's' : ''));
    });
});

Online sample updated with feedback suggestions

    
14.07.2014 / 16:48