Reputation: 11
I want to create a list with check box dynamically. For that i created list item, check box,text node dynamically.
My problem is, I want to append checkbox and textnode inside List item. How to do this?
In Script:
var name=x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
var list = document.createElement( "li" );
var cb = document.createElement( "input" );
cb.type = "checkbox";
cb.id = "c1";
cb.value = name;
cb.checked = false;
var text = document.createTextNode( name );
In Body:
<ul id="list" >
</ul>
I want to do like,
<li><input type="checkbox">Tamil</li>
dynamically from javascript.
For that i tried like,
document.getElementById( 'list' ).appendChild(list);
document.getElementById( 'list' ).appendChild(cb);
document.getElementById( 'list' ).appendChild(text);
But it is not appended in li
.
How to append these correctly?
Upvotes: 0
Views: 4507
Reputation: 18344
You have to create a checkbox dynamically, create a list item (<li>
) dynamically, append the checkbox to the <li>
and the <li>
to the UL
Something Like:
var name = "Test"; //or whatever you want, from another textbox for instance
//Create a new <li> dynamically
var newLi = document.createElement('li');
//Create checkbox dynamically
var checkBox = cb = document.createElement( "input" );
cb.type = "checkbox";
cb.id = "c1";
cb.value = name;
cb.checked = false;
//Append the checkbox to the li
newLi.appendChild(cb);
//Create the text node after the the checkbox
var text = document.createTextNode(name);
//Append the text node to the <li>
newLi.appendChild(text);
//Append the <li> to the <ul>
var ul = document.getElementById("test");
ul.appendChild(newLi);
You started correct, then forgot to create a new <li>
Upvotes: 3
Reputation: 184
var name=x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
var list = document.createElement( "li" );
var cb = document.createElement( "input" );
cb.type = "checkbox";
cb.id = "c1";
cb.value = name;
cb.checked = false;
// then
list.appendChild(cb);
list.innerHTML+=name;//or if you want,create the textnode 'text' and appendChild again
var lists=document.getElementById('list');
lists.appendChild(list);
Upvotes: 1
Reputation: 58521
I would recommend using jQuery or another similar library. This will help to ensure cross browser compatibilty, and simplify your coding. With jQuery you can do it like this...
// create something, and appendTo something else
$('<li />').appendTo('body')
// select something, and append something else to it
$('li').append( $('<input />').attr({type:'checkbox'}) )
Upvotes: 0