简体   繁体   中英

Creating checkbox when a checkbox is selected in javascript

    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);
    }
};

HTML:

    <ul id="container">
    <li>
        <input type="checkbox">
    </li>
    <li>
        <input type="checkbox">
    </li>
    <li>
        <input type="checkbox">
    </li>
</ul>

I have create three checkbox. When one checkbox is selected another threebox appears beneath it and so on. Now the problem is how to assign unique id and onclick event to every checkbox

First, I would use jQuery (or other framework) to do it. In this example, I use jQuery.
Then, to create an element into your document do as follow:

function addCheckboxes(){
    /* this will create the box but will not place it into your document */
    var newCheckboxes = $('<input type="checkbox" /><input type="checkbox" /><input type="checkbox" />');

    /* this will put the code in the docuement */
    $('#container').append(newCheckboxes);
}

Then to attach events, use the jQuery.live() function:

    /* this will attach the click event */
    $('#container input').live('click', function(){
        addCheckboxes();
    });

Please note that this will assign the same event to all checkboxes.
If you wanted to attach a different event to each checkboxes, you should find a way to iterate on each checkbox inside the addCheckboxes function, or create each box separately, and attach the event everytime you create one.

Feel free to create a jsFiddle on this website if you want to run your code online and share it with us.

Have done for adding rows and generating IDs for each row dynamically and attaching scripts for adding and removing rows functionality. Check this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM