Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating the checkbox dynamically using JavaScript?

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> 
like image 831
Sandeep Giri Avatar asked May 14 '09 22:05

Sandeep Giri


People also ask

How do you create a checkbox in JavaScript?

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.

How check if checkbox is dynamic?

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.

How can I get dynamic checkbox checked value in jQuery?

$('#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] ); } });


1 Answers

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); 
like image 52
Quentin Avatar answered Sep 24 '22 12:09

Quentin