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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16744594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:41:51  来源:igfitidea点击:

How to use jQuery to add form elements dynamically

jqueryhtmlforms

提问by pgtips

Here is my html:

这是我的 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>

And this is my jquery:

这是我的 jquery:

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

The #extraPerson is hidden in the css.

#extraPerson 隐藏在 css 中。

It adds the div when the link is clicked. However, I want it to continue adding the same div each time the link is clicked. How do I do this? Even better if it appends the number to the form input names. Eg firstname3, firstname4 etc.

单击链接时,它会添加 div。但是,我希望它在每次单击链接时继续添加相同的 div。我该怎么做呢?如果将数字附加到表单输入名称,那就更好了。例如名字 3、名字 4 等。

回答by PSL

Try this way:-

试试这个方法:-

Demo

演示

HTML

HTML

Create a template extraPersonTemplateand use it to construct further. Add a container tyo your content section.

创建一个模板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

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();    
}

Small Css

小CSS

.extraPersonTemplate {
    display:none;
}

回答by Pevara

I came up with a solution of my own. Plenty of comments, but feel free to ask.

我想出了一个自己的解决方案。很多评论,但请随意提问。

$(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();
         });
    })

I like the fact that @PSL uses a template though, might be a better an easier solution. Do note that you would need to add the code to update the person number in there...

我喜欢@PSL 使用模板的事实,这可能是一个更好、更简单的解决方案。请注意,您需要添加代码来更新那里的人员编号...

A fiddle: http://jsfiddle.net/Mk7MQ/

小提琴:http: //jsfiddle.net/Mk7MQ/

回答by Igor Demenchuk

both Pevara and PSL scripts not working correctly all new lines names/ids are same as first one so there is no way to get the values later from them in the script .substring(index+9,1)should be corrected to .substring(index+9,index+10)but even than next will be always ==2 as $person.html(); haven't been really changed

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

here are 3 solution options : https://www.jqueryscript.net/form/jQuery-Plugin-To-Dynamically-Add-More-Form-Fields-czMore.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.codexworld.com/add-remove-input-fields-dynamically-using-jquery/

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

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