tags:

views:

321

answers:

2

The following code adds a checkbox and a label to the calling node.
My question lies in the label.click function. Whenever the label is clicked I want to change the state of the matching checkbox. What happens however is that the checkbox always ends up unchecked. For debugging purposes I now always explicitly set it to checked.

When I step through the code with firebug I see that the checkbox gets checked and then, when leaving the function it gets unchecked again.

Any ideas?

jQuery.fn.AddEndOrStartWith = function(selected, id, action) {
 var checkBox = $('<input type="checkbox"></input>');
 checkBox.attr("id", id + action);
 checkBox.addClass(action + "CheckBox");
 checkBox.attr("for", id);

 var label = $('<label></label>');
 label.attr("for", id + action);

 if (selected) {
  checkBox.attr("checked", "checked");
  label.addClass("lockerClosed");
 } else {
  label.addClass("lockerOpen");
 }

 $(this).append(label);
 $(this).append(checkBox);

 label.click(function() {
  /*alert(checkBox.attr("checked"));*/
  checkBox.attr("checked", "checked");
  /*return true;*/
  /*alert(checkBox.attr("checked"));*/
 });
}
+4  A: 

You need to prevent the default action in your label click handler. Think this should do it:

label.click(function() {
     checkBox.attr("checked", "checked");
     return false;
});

What's going on is that because your label is set up with its for referring to the checkbox correctly, the default action when clicking on it is to toggle the checkbox.

Though, um, if that's all you're trying to do with your click handler, I guess you could just not even use a click handler. But I'm not sure whether that's the case.

chaos
Yep, I found it out too. Byt you actually knew why :)
borisCallens
Well, no, there's more going on but that was not really relevant for the question.
borisCallens
A: 

After two afternoons of searching I put it on SO and then within a few minutes I found it myself..

Apparently when setting the id of the checkbox, setting the for attribute on the label and then returning positive on the click function somehow makes it false. By making the click function return false, I break the cycle without invalidating my HTML.

Final code:

jQuery.fn.AddEndOrStartWith = function(selected, id, action) {
 var checkBox = $('<input type="checkbox"></input>');
 checkBox.attr("id", id + action);
 checkBox.addClass(action + "CheckBox");

 var label = $('<label></label>');
 label.attr("for", id + action);

 if (selected) {
  checkBox.attr("checked", "checked");
  label.addClass("lockerClosed");
 } else {
  label.addClass("lockerOpen");
 }

 $(this).append(label);
 $(this).append(checkBox);

 label.click(function() {
  checkBox.attr("checked", !checkBox.attr("checked"));
  return false;
 });
}
borisCallens