使用jQuery添加新输入

时间:2013-02-13 23:53:53

标签: jquery

我的表单上有一个名为roomfac1的下拉菜单,我希望在用户点击时添加 roomfac2 roomfac3 ...(重复的下拉菜单) 添加按钮。我如何使用jQuery实现这一目标?除此之外,我还希望用户动态删除新创建的输入。

我在这里上传了我的代码:http://jsfiddle.net/ecRXP/2/

<select name="roomFac1" id="roomFac1">
  <option selected="selected">Any</option>
</select>
<input type="button" value="Add" class="pmbtn" id="addFac"/>
<input type="button" value="Remove" class="pmbtn" id="removeFac"/>

3 个答案:

答案 0 :(得分:3)

$(document).ready(function(){
    $('#addFac').click(function(){
        var $objs = $('select[name*=roomFac]');
        var n = $objs.size() + 1;
        var $obj = $objs.first().clone();
        $obj.attr('name', 'roomFac'+n).attr('id', 'roomFac'+n);
        $obj.appendTo($('body'));
    });
    $('#removeFac').click(function(){
        var $objs = $('select[name*=roomFac]');
        if($objs.size() > 1){
           $objs.last().remove();
        }
    });
});

这里是小提琴:http://jsfiddle.net/kfm5b/2/

答案 1 :(得分:1)

Example on jsFiddle

HTML:

<form>
    <div class="add">
        <a href="#" id="add">Add</a>
    </div>
    <div class="row">
        <select name="roomFac1" id="roomFac1">
            <option selected="selected">Any</option>
        </select>
    </div>
</form>

JS:

var $form = $("form"),
    $firstRow = $(".row:first"),
    totalRows;

$("form").on("click", ".delete", function (e) {
    e.preventDefault();

    $(this).closest("div").remove();
});

$("#add").on("click", function (e) {
    var $clonedRow = $firstRow.clone(),
        totalRows = "1",
        newNum;

    e.preventDefault();

    totalRows = $(".row").length;
    newNum = parseInt(totalRows, 10) + 1;

    $clonedRow.find("select").attr("name", "roomFac" + newNum);
    $clonedRow.find("select").attr("id", "roomFac" + newNum);
    $clonedRow.append('<a href="#" class="delete">Delete</a>');
    $form.append($clonedRow);
});

答案 2 :(得分:1)

我认为您可以使用.clone,如下所示:

var roomFacCount = 1;

$('#addFac').on('click', function() {
    var $lastRoomFac = $('#roomFac' + roomFacCount);
    roomFacCount++;
    $lastRoomFac.after($lastRoomFac.clone(true, true).attr('id', 'roomFac' + roomFacCount));
});

$('#removeFac').on('click', function() {
    if (roomFacCount > 1) {
        var $lastRoomFac = $('#roomFac' + roomFacCount);
        roomFacCount--;
        $lastRoomFac.remove();
    }
});

Demo on jsfiddle