Add checkbox with jquery in div

I want to add a checkbox in a div to another div (with id = "# sensorList") and then bind some event handlers to it. I do that 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 that everything is fine, but if I click on the checkbox, it will not switch to the checked status!

Any idea? Thank you in advance.


I'm sorry, I realized where the problem is. I was not able to set the checkbox because I had a click handler on the div called sensorId and I did stupidly: event.preventDefault () (by default there is no behavior on clicking on the div !!!)

+4
source share
2 answers

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

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

This works for me. Check out jsfiddle: http://jsfiddle.net/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); });​ 
+2
source

Source: https://habr.com/ru/post/1441611/


All Articles