admin管理员组

文章数量:1291319

I want to add a checkbox into a div into another div (with id="#sensorList"), and then bind some event handlers to it. I do in this way

/* Add div */
$("#sensorList").append($('<div>', { id : sensorId})
.addClass("sensorListItem")
.text(sensorId)
);

/* Adds visibile checkbox */
$("#"+sensorId).append($('<input>', { id : sensorId + "VisibleCheckbox", type:"checkbox", name: sensorId + "VisibleCheckbox"}));

It seems to work fine, but if I click on checkbox, it doesn't switch to checked status!

Any idea? Thank you in advance.


I'm so sorry, I figured out where the problem was. I was unable to see the checkbox checked because I had a click handler on div called sensorId, and I stupidly did: event.preventDefault() (there is no default behaviour clicking on a div!!!)

I want to add a checkbox into a div into another div (with id="#sensorList"), and then bind some event handlers to it. I do in this way

/* Add div */
$("#sensorList").append($('<div>', { id : sensorId})
.addClass("sensorListItem")
.text(sensorId)
);

/* Adds visibile checkbox */
$("#"+sensorId).append($('<input>', { id : sensorId + "VisibleCheckbox", type:"checkbox", name: sensorId + "VisibleCheckbox"}));

It seems to work fine, but if I click on checkbox, it doesn't switch to checked status!

Any idea? Thank you in advance.


I'm so sorry, I figured out where the problem was. I was unable to see the checkbox checked because I had a click handler on div called sensorId, and I stupidly did: event.preventDefault() (there is no default behaviour clicking on a div!!!)

Share Improve this question edited Oct 23, 2012 at 17:52 dar0x asked Oct 23, 2012 at 17:30 dar0xdar0x 3612 gold badges6 silver badges10 bronze badges 1
  • 1 Are you sure you don't have any other code preventing the default action of the checbox, or that you simply placed another element on top of it. – adeneo Commented Oct 23, 2012 at 17:37
Add a ment  | 

2 Answers 2

Reset to default 3

try some long hand and see if it works...

$("#"+sensorId).append('<input type="checkbox" id="' + sensorId + 'VisibleCheckbox" name="'  + sensorId + 'VisibleCheckbox" >');

It works for me. Check out the jsfiddle: http://jsfiddle/pVjNM/

var sensorId = "one";

/* Add div */
$("#sensorList").append($('<div>', { id : sensorId })
.addClass("sensorListItem")
.text(sensorId)
);

/* Adds visibile checkbox */
$("#"+sensorId).append($('<input>', { id : sensorId + "VisibleCheckbox", type:"checkbox", name: sensorId + "VisibleCheckbox"}));

$("input[type=checkbox]").each(function(){
    this.click();
    console.log("Should be true:", this.checked);
});


$("input[type=checkbox]").each(function(){
    this.click();
    console.log("Should be false:", this.checked);
});​

本文标签: javascriptAdd a checkbox with jquery into a divStack Overflow