I am trying to create a checkbox dynamically using following HTML/JavaScript. Any ideas why it doesn't work?
<div id="cb"></div> <script type="text/javascript"> var cbh = document.getElementById('cb'); var val = '1'; var cap = 'Jan'; var cb = document.createElement('input'); cb.type = 'checkbox'; cbh.appendChild(cb); cb.name = val; cb.value = cap; cb.appendChild(document.createTextNode(cap)); </script>
Creating checkbox object: We can create checkbox object through javascript. To create <input type = “checkbox”> element use document. createElement() method. After creation use the appendChild() method to append it to the particular element (such as div) to display it.
Answer: Use the jQuery prop() method You can use the jQuery prop() method to check or uncheck a checkbox dynamically such as on click of button or an hyperlink etc. The prop() method require jQuery 1.6 and above.
$('#envoyer'). click(function(e){ var myArray = new Array(3); for ( var j = 0; j < 3; j++) { var check=$('input:checkbox[name=checkbox'+j+']').is(':checked'); if(check==true) myArray[j]=$('input:checkbox[name=checkbox'+j+']'). val(); // Alert Current Selection // alert('check ' + " " + myArray[j] ); } });
You're trying to put a text node inside an input element.
Input elements are empty and can't have children.
... var checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.name = "name"; checkbox.value = "value"; checkbox.id = "id"; var label = document.createElement('label') label.htmlFor = "id"; label.appendChild(document.createTextNode('text for label after checkbox')); container.appendChild(checkbox); container.appendChild(label);
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