populate list of option when a checkbox is selected using javascript
Need to populate a list of options with checkbox when a checkbox is clicked. let consider there are three checkbox when a checkbox is selected beneath that 开发者_StackOverflow中文版checkbox a list of options with checkbox should appear. if a checkbox is selected then beneath that and so on........
how to do this in javascript.....any help..........
If your lists are static, I would define them ahead of time in divs, and set the visibility to false. Then, in your OnClick methods of the checkboxes, simply set the visibility to true when necessary.
Since you asked a very generic question, I'll give a very generic answer.
Example: http://jsfiddle.net/NFs4K/3/
var container = document.getElementById('container'),
template = '<li>\
<input type="checkbox">\
</li>\
<li>\
<input type="checkbox">\
</li>\
<li>\
<input type="checkbox">\
</li>';
container.onchange = function(e) {
var event = e || window.event,
target = event.srcElement || event.target;
if( target.checked && target.parentNode.getElementsByTagName('ul').length === 0 ) {
var ul = document.createElement('ul');
ul.innerHTML = template;
target.parentNode.appendChild(ul);
} else {
var ul = target.parentNode.getElementsByTagName('ul')[0];
target.parentNode.removeChild(ul);
}
};
If you want a better answer, please ask a more detailed question.
EDIT: Removed the checkboxes
variable. It wasn't being used.
EDIT: I updated so that it only appends the sub-list when checked, and only the first time it is checked.
EDIT: Updated to remove all nested levels when unchecked.
精彩评论