Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Binding change to multiple checkboxes

Tags:

jquery

binding

For a little bit of background, I have multiple checkboxes, each weighted with a different "score". When the checkbox is changed, I need to compute the score. I thought something like the following would work but it does not look like the .change event is being bound properly.

$(document).ready(function() {
   bindSomeCheckboxes();
});

function bindSomeCheckboxes() {
    var score=0;
    var checkboxes = {
        "id_1" : 3,
        "id_2" : 1,
        "id_3" : 2,
        "id_4" : 5
    };

    $.each(checkboxes, function(key, value) {
        $("#"+key).change(function(key,value) {
            if ($("#"+key).is(':checked')) {
                //add this ids value to score
            } else {
                //subtract value from score
            }
        });
    });
}  

I know that it is looping through the array correctly, but an alert in .change is never being seen.

like image 224
ftdysa Avatar asked Oct 13 '10 14:10

ftdysa


Video Answer


1 Answers

I recommend you to add a container and select all checkboxes at once.

And as for your question, the signature of the event is wrong, the correct is function(e){}. Also, you have to check if the element is checked, and not clicked.

$("#chk").change(function(e){
    if ($(this).is(":checked"))
        alert("checked");
    else
        alert("not checked");
});

To make it easier, use a container

Sample HTML

<div id="checks">
    <input type="checkbox" id="chk1" />
    <input type="checkbox" id="chk2" />
    <input type="checkbox" id="chk3" />
    <input type="checkbox" id="chk4" />
</div>

And for the scores, I prefer to set data on the elements, example:

$("#chk1").data("Score", 3);
$("#chk2").data("Score", 1);
$("#chk3").data("Score", 2);
$("#chk4").data("Score", 5);

$("#checks :checkbox").change(function(e){
    if ($(this).is(":checked"))
        alert("checked Score: " + $(this).data("Score"));
    else
        alert("not checked Score: " + $(this).data("Score"));
});
  • See this example on jsFiddle.
  • jQuery change event
  • :checked selector
  • .data
like image 95
BrunoLM Avatar answered Sep 30 '22 20:09

BrunoLM