【问题标题】:jQuery add and remove inputsjQuery 添加和删除输入
【发布时间】:2011-01-24 17:12:14
【问题描述】:

我需要修改以下代码,以便我可以将它们用于同一页面上的单独迭代。下面的按钮代码是+- 图标here。目前,它们发生冲突,我仍然需要添加和删除整个迭代框。

这是我的脚本代码:

$('#btnAdd').click(function() {
    var count = $('.clonedIteration').length;
    var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
    var newNum = new Number(num + 1); // the numeric ID of the new input field being added
    // create the new element via clone(), and manipulate it's ID using newNum value
    //add parent so that the adding is only specific to those within the class
    var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
    // manipulate the name/id values of the input inside the new element
    newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + count);
    //prepend table code
    $('#input' + num).append('<tr><td colspan="2"><label>');
    // insert the new element after the last "duplicatable" input field
    $('#input' + num).after(newElem);
    //prepend table code
    $('#input' + newNum).append('</label></td></tr>');
    // enable the "remove" button
    $('#btnDel').attr('disabled', '');
    // business rule: you can only add XXX times
    if (newNum == 5) $('#btnAdd').attr('disabled', 'disabled');


    return false
});

$('#btnDel').click(function() {
    var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
    $('#input' + 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');

    return false
});

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

【问题讨论】:

    标签: jquery dynamic add elements


    【解决方案1】:

    这是一个关于 jsfiddle 的例子:http://jsfiddle.net/LetZh/1/ 你的代码有点复杂。我没有实现你拥有的所有东西。

    编辑

    http://jsfiddle.net/LetZh/2/我对js代码做了一些更正。

    【讨论】:

    • 嘿,cronos,你让我大吃一惊!这简直太棒了!谢谢!
    • 只是为了与您核实一下,您如何确保每次迭代至少有一个文本框和至少 2 个迭代可以使用?意思是如果我有 2 次迭代,我不能删除迭代,如果我只有一个左,我不能删除文本框。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2011-03-24
    相关资源
    最近更新 更多