jQuery 动态添加表单域,删除表单域

jQuery Dynamic Add Form Field, Remove Form Field

本文关键字:表单 删除 动态 jQuery 添加      更新时间:2023-09-26

您好,在从本教程中获得灵感后,我正在尝试添加新的表单字段并删除表单字段 - http://bootsnipp.com/snipps/dynamic-form-fields

我当前的问题是按时间顺序删除和重置所有值。

<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
           <label class="control-label" for="field1">Nice Multiple Form Fields</label>
           <div class="controls" id="profs"> 
             <div class="input-append">
               <input autocomplete="off" class="span3" id="field1" name="prof1" type="text" placeholder="Type something (it has typeahead too)" data-provide="typeahead" data-items="8" 
data-source='["Aardvark","Beatlejuice","Capricorn","Deathmaul","Epic"]'/><button id="b1" onClick="addFormField()" class="btn btn-info" type="button">+</button>
             </div>
             <br /><small>Press + to add another form field :)</small>
           </div>
         </div>

Javascript :-

var next = 1;
function addFormField(){
    var addto = "#field" + next;
    next = next + 1;
    var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b1" onClick="$(this).parent().remove();" class="btn btn-info" type="button">+</button>';
    var newInput = $(newIn);
    $(addto).after(newInput);
    $("#field" + next).attr('data-source',$(addto).attr('data-source'));
    $("#count").val(next);  
}

父元素被删除,但下一个计数器未正确重置。 在隐藏和所有新创建的表单中:-

仅添加演示:- http://bootsnipp.com/snipps/dynamic-form-fields

添加一个带有错误的删除演示:- http://jsfiddle.net/6dCrT/2/

有人可以帮我吗?

谢谢

尝试:

function addFormField(){
    var addto = "#field" + next;
    next = next + 1;
    var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b'+next+'" onClick="$(this).prev().remove();$(this).remove();" class="btn btn-info" type="button">-</button>';
    var newInput = $(newIn);
    console.log(addto);
    $(addto).after(newInput);
    if(next>1)
        $("button#b"+next).after(newInput);
    $("#field" + next).attr('data-source',$(addto).attr('data-source'));
    $("#count").val(next);  
}

演示小提琴

在我的示例中,我正在构建一个表单,如果用户有多个狗,则可以添加多个输入名称。

    var counter = 0
    jQuery(function () {
      $(".newDog").click(function(){
        counter ++;
        if (counter < 4) {
          var elem = $("<input/>",{
            type: "text",
            name: `dogname${counter}`
        });
        } else {
          alert("You can only add 4 Dog Names")
        }
        
        var removeLink = $("<span/>").html("X").click(function(){
            $(elem).remove();
            $(this).remove();
            counter --;
        });
        
        $(".dogname-inputs").append(elem).append(removeLink);
    });
    })

https://stackoverflow.com/users/714969/kevin-bowersox 提到的全部信用