I've been doing a lot of adding to the DOM using jQuery of late (don't ask - my preferred method using jsrender wouldn't work) and as such I've had to remember how to set a checkbox value dynamically.
Generally speaking I create a blank object and pass it an object to give it its attributes but that just doesn't work with checked
... things got even stranger when I clocked that my inputs needed to be nested within a div so I decided that I'd create my blank node, pass it its attributes and then chain a prop call (which takes a true or false value) and came up with this:
var contravention = false $("#input-holder") .append($("<div></div>", { "id": "contravention"}) .append($("<label></label>", { "for": "contravention", "text": "Contravention" })) .append($("<input/>", { "id":"contravention", "name":"contravention", "type":"checkbox", "value": "true" }).prop("checked", contravention) ));
The indentation helped a lot as well! Demo here.
No comments:
Post a Comment