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.
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"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With