如何使用jQuery动态添加表单元素

16

这是我的HTML代码:

<div id="extraPerson">
    <div class="controls controls-row">
      <input class="span3" placeholder="First Name" type="text" name="firstname2">
      <input class="span3" placeholder="Last Name" type="text" name="lastname2">     
         <select class="span2" name="gender2"><option value="Male">Male</option><option           value="Female">Female</option></select>   
        ...ETC
    </div>
</div>

<a href="#" id="addRow"><i class="icon-plus-sign icon-white"></i> Add another family member</p></a>

这是我的jQuery代码:

<script>
    $(document).ready(function(){
        $('#addRow').click(function(){
            $("#extraPerson").slideDown();
         });
    })
</script>

#extraPerson在CSS中被隐藏。

当链接被点击时,它会添加一个div。但是,我希望每次单击链接时它都能继续添加相同的div。我该怎么做?最好还能将数字附加到表单输入名称中。例如firstname3、firstname4等。


extraPerson并不是在“添加”任何东西,它已经存在了。你是如何创建其他形式的? - tymeJV
1
更新答案,包括不同的表单名称。 - PSL
3个回答

33

尝试这种方式:-

演示

HTML

创建一个模板extraPersonTemplate并使用它来构建更多内容。将容器添加到您的内容部分。

<div class="extraPersonTemplate">
    <div class="controls controls-row">
        <input class="span3" placeholder="First Name" type="text" name="firstname2">
        <input class="span3" placeholder="Last Name" type="text" name="lastname2">
        <select class="span2" name="gender2">
            <option value="Male">Male</option>
            <option value="Female">Female</option>
        </select>
    </div>
</div>
<div id="container"></div>

JS

  $(document).ready(function () {
     $('<div/>', {
         'class' : 'extraPerson', html: GetHtml()
     }).appendTo('#container'); //Get the html from template
     $('#addRow').click(function () {
           $('<div/>', {
               'class' : 'extraPerson', html: GetHtml()
     }).hide().appendTo('#container').slideDown('slow');//Get the html from template and hide and slideDown for transtion.

     });
 })
 function GetHtml() //Get the template and update the input field names
{
      var len = $('.extraPerson').length;
    var $html = $('.extraPersonTemplate').clone();
    $html.find('[name=firstname]')[0].name="firstname" + len;
    $html.find('[name=lastname]')[0].name="lastname" + len;
    $html.find('[name=gender]')[0].name="gender" + len;
    return $html.html();    
}

小型CSS

.extraPersonTemplate {
    display:none;
}

更新了答案,为每一行使用不同的输入名称。 - PSL
1
你好 @PSL,针对这个例子,我该如何删除插入的行? - adventistapr

5
我想出了自己的解决方案。有很多评论,但请随意提问。
$(document).ready(function(){
        $('#addRow').click(function(){
            // get the last person and html html
            var $person = $('.person').last();
            var person = $person.html();
            // find the number
            var index = person.indexOf('firstname');
            var number = parseInt(person.substring(index+9,1));
            var next = number+1;
            // replace the number
            // for firstname
            person.replace('firstname'+number, 'firstname'+next);
            // for lastname
            person.replace('lastname'+number, 'lastname'+next);
            // for gender
            person.replace('gender'+number, 'gender'+next);
            // insert the new person after the last one
            $person.after($('<div class="person">'+person+'</div>'));            
            // get the new person
            var $new = $('.person').last();
            // hide it
            $new.hide();
            // reset the values
            $new.find('input, select').val('');
            // fade it in
            $new.slideDown();
         });
    })

我喜欢@PSL使用模板的事实,这可能是更好更容易的解决方案。请注意,您需要添加代码来更新其中的人数...

一个演示: http://jsfiddle.net/Mk7MQ/


0

Pevara和PSL脚本都无法正常工作,所有新行的名称/ID与第一个相同,因此无法在脚本中稍后获取它们的值。 .substring(index + 9,1)应更正为.substring(index + 9,index + 10),但即使如此,下一个将始终== 2,因为$ person.html();实际上没有改变

这里有3个解决方案选项: https://www.jqueryscript.net/form/jQuery-Plugin-To-Dynamically-Add-More-Form-Fields-czMore.html

https://www.codexworld.com/add-remove-input-fields-dynamically-using-jquery/

https://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接