开发者

Dynamically adding two form elements with jQuery

I am trying to create two form elements when th开发者_高级运维e user clicks a button, which he can do 5 times, but I am new to jQuery so I am running into problems,

here is the code:

$(document).ready(function() {
    $('#btnAdd').click(function() {
        var num     = $('.clonedInput').length; 
        var numTwo     = $('.clonedInputTwo').length; 
        var newNum  = new Number(num + 1);      

        var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
        var newElemTwo = $('#inputTwo' + numTwo).clone().attr('id', 'input' + newNum);


        newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
        newElemTwo.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);


        $('#input' + num).after(newElem);
        $('#inputTwo' + numTwo).after(newElemTwo);

        $('#btnDel').attr('disabled','');

        if (newNum == 5)
            $('#btnAdd').attr('disabled','disabled');
    });

        $('#btnDel').click(function() {
            var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
            $('#input' + num).remove();     // remove the last element
            $('#inputTwo' + num).remove();     // remove the last element

            // enable the "add" button
            $('#btnAdd').attr('disabled','');

            // if only one element remains, disable the "remove" button
            if (num-1 == 1)
                $('#btnDel').attr('disabled','disabled');
        });

        $('#btnDel').attr('disabled','disabled');
    });

The HTML:

<form id='myForm'>
    <div id='input1' style='margin-bottom:4px;' class='clonedInput'>
        Name: <input type='text' name='name1' id='name1' />
    </div>
    <div id='inputTwo1' style='margin-bottom:4px;' class='clonedInputTwo'>
        School: <input type='text' name='nameTwo1' id='nameTwo1' />
    </div>
    <div>
        <input type='button' id='btnAdd' value='add another name' />
        <input type='button' id='btnDel' value='remove name' />
    </div>
</form>

When I click the button it works once, then it just proceeds to create name elements, and no school elements!


var newElemTwo = $('#inputTwo' + numTwo).clone().attr('id', 'input' + newNum);

should be

var newElemTwo = $('#inputTwo' + numTwo).clone().attr('id', 'inputTwo' + newNum);

Take a look (thanks to MvanGeest)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜