开发者

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');
开发者_JAVA技巧        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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜