【问题标题】:Add / remove input field dynamically with jQuery使用 jQuery 动态添加/删除输入字段
【发布时间】:2012-02-07 08:38:17
【问题描述】:

我想使用 jquery 来构建一个动态添加/删除表单。 它应该看起来像:

需要名称类型吗?

示例输入:

  • 需要名称类型吗?
  • Tony 管理员已选中(复选框)删除

我得到的是添加/删除输入框的示例,它如何转换为我的想法?我必须使用多列表吗?感谢您的热心帮助

    <html>
<head>
<title>jQuery add / remove textbox example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
    div{
        padding:8px;
    }
</style>

</head>

<body>

<h1>jQuery add / remove textbox example</h1>

<script type="text/javascript">

$(document).ready(function(){

    var counter = 2;

    $("#addButton").click(function () {

    if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
    }   

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
          '<input type="text" name="textbox' + counter + 
          '" id="textbox' + counter + '" value="" >');

    newTextBoxDiv.appendTo("#TextBoxesGroup");


    counter++;
     });

     $("#removeButton").click(function () {
    if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

    counter--;

        $("#TextBoxDiv" + counter).remove();

     });

     $("#getButtonValue").click(function () {

    var msg = '';
    for(i=1; i<counter; i++){
      msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
    }
          alert(msg);
     });
  });
</script>
</head><body>

<div id='TextBoxesGroup'>
    <div id="TextBoxDiv1">
        <label>Textbox #1 : </label><input type='textbox' id='textbox1' >
    </div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>

</body>
</html>

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    我冒昧地整理了一个 jsFiddle,说明了使用 jQuery 构建自定义表单的功能。 Here it is...

    编辑:更新了 jsFiddle 以包括每个字段的删除按钮。

    编辑:根据最后评论中的请求,来自 jsFiddle 的代码如下。

    编辑:根据 Abhishek 的评论,我已经更新了 jsFiddle(和下面的代码)以适应可能出现重复字段 ID 的情况。

    HTML:

    <fieldset id="buildyourform">
        <legend>Build your own form!</legend>
    </fieldset>
    <input type="button" value="Preview form" class="add" id="preview" />
    <input type="button" value="Add a field" class="add" id="add" />
    

    JavaScript:

    $(document).ready(function() {
        $("#add").click(function() {
            var lastField = $("#buildyourform div:last");
            var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1;
            var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
            fieldWrapper.data("idx", intId);
            var fName = $("<input type=\"text\" class=\"fieldname\" />");
            var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Paragraph</option></select>");
            var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
            removeButton.click(function() {
                $(this).parent().remove();
            });
            fieldWrapper.append(fName);
            fieldWrapper.append(fType);
            fieldWrapper.append(removeButton);
            $("#buildyourform").append(fieldWrapper);
        });
        $("#preview").click(function() {
            $("#yourform").remove();
            var fieldSet = $("<fieldset id=\"yourform\"><legend>Your Form</legend></fieldset>");
            $("#buildyourform div").each(function() {
                var id = "input" + $(this).attr("id").replace("field","");
                var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
                var input;
                switch ($(this).find("select.fieldtype").first().val()) {
                    case "checkbox":
                        input = $("<input type=\"checkbox\" id=\"" + id + "\" name=\"" + id + "\" />");
                        break;
                    case "textbox":
                        input = $("<input type=\"text\" id=\"" + id + "\" name=\"" + id + "\" />");
                        break;
                    case "textarea":
                        input = $("<textarea id=\"" + id + "\" name=\"" + id + "\" ></textarea>");
                        break;    
                }
                fieldSet.append(label);
                fieldSet.append(input);
            });
            $("body").append(fieldSet);
        });
    });
    

    CSS:

    body
    {
        font-family:Gill Sans MT;
        padding:10px;
    }
    fieldset
    {
        border: solid 1px #000;
        padding:10px;
        display:block;
        clear:both;
        margin:5px 0px;
    }
    legend
    {
        padding:0px 10px;
        background:black;
        color:#FFF;
    }
    input.add
    {
        float:right;
    }
    input.fieldname
    {
        float:left;
        clear:left;
        display:block;
        margin:5px;
    }
    select.fieldtype
    {
        float:left;
        display:block;
        margin:5px;
    }
    input.remove
    {
        float:left;
        display:block;
        margin:5px;
    }
    #yourform label
    {
        float:left;
        clear:left;
        display:block;
        margin:5px;
    }
    #yourform input, #yourform textarea
    {
        float:left;
        display:block;
        margin:5px;
    }
    

    【讨论】:

    • 删除功能正是我想要的,我正在尝试修改您的代码以在每一行中添加一个字段
    • 好像不用修改jquery脚本,加个input元素就好了。
    • 我想知道第二个的名字是什么,因为同一行有两个文本框
    • 如果添加2个字段,然后删除第一个,然后再添加1个字段,就会有2个相同ID的元素,如何解决?
    • 欣赏@AbhishekPandey 的客气话
    【解决方案2】:

    您需要创建元素。

    input = jQuery('<input name="myname">');
    

    然后将其附加到表单中。

    jQuery('#formID').append(input);
    

    要删除输入,请使用删除功能。

    jQuery('#inputid').remove();
    

    这是基本思想,你可能有 feildsets 来代替它,或者可能将它附加在特定元素之后,但这是真正动态构建任何东西的方法。

    【讨论】:

    • 然后,$("#TextBoxDiv" + rowID).remove();是为了移除吗?
    【解决方案3】:

    jQuery 代码

    $(document).ready(function() {
        var max_fields      = 10; //maximum input boxes allowed
        var wrapper         = $(".input_fields_wrap"); //Fields wrapper
        var add_button      = $(".add_field_button"); //Add button ID
    
        var x = 1; //initlal text box count
        $(add_button).click(function(e){ //on add input button click
            e.preventDefault();
            if(x < max_fields){ //max input box allowed
                x++; //text box increment
                $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
            }
        });
    
        $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
            e.preventDefault(); $(this).parent('div').remove(); x--;
        })
    });
    

    HTML 代码

    <div class="input_fields_wrap">
        <button class="add_field_button">Add More Fields</button>
        <div><input type="text" name="mytext[]"></div>
    </div>
    

    【讨论】:

    • 很好的答案,很容易集成到我的网站中。
    • 你能解释一下如何填充现有的字符串列表吗?
    • 哇,很好的答案,你太棒了!,谢谢。
    【解决方案4】:

    你可以这样做:

     $("#addButton").click(function () {
    
        if(counter>10){
                alert("Only 10 textboxes allow");
                return false;
        }   
    
        var newTextBoxDiv = $(document.createElement('div'))
             .attr("id", 'TextBoxDiv' + counter);
    
        newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
              '<input type="text" name="textbox' + counter + 
              '" id="textbox' + counter + '" value="" >');
    
        newTextBoxDiv.appendTo("#TextBoxesGroup");
    
    
        counter++;
         });
    
         $("#removeButton").click(function () {
        if(counter==1){
              alert("No more textbox to remove");
              return false;
           }   
    
        counter--;
    
            $("#TextBoxDiv" + counter).remove();
    
         });
    

    参考现场演示http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/

    【讨论】:

      【解决方案5】:

      您可以执行以下操作:

      //when the Add Field button is clicked
      $("#add").click(function (e) {
      //Append a new row of code to the "#items" div
        $("#items").append('<div><input type="text" name="input[]"><button  class="delete">Delete</button></div>');
      });
      

      详细教程http://voidtricks.com/jquery-add-remove-input-fields/

      【讨论】:

      • 差不多 5 年后,这对我来说非常有用,谢谢。
      【解决方案6】:

      这是我的JSFiddle,带有更正的换行符,或在下面查看。

      $(document).ready(function() {
      
      var MaxInputs       = 2; //maximum extra input boxes allowed
      var InputsWrapper   = $("#InputsWrapper"); //Input boxes wrapper ID
      var AddButton       = $("#AddMoreFileBox"); //Add button ID
      
      var x = InputsWrapper.length; //initlal text box count
      var FieldCount=1; //to keep track of text box added
      
      //on add input button click
      $(AddButton).click(function (e) {
              //max input box allowed
              if(x <= MaxInputs) {
                  FieldCount++; //text box added ncrement
                  //add input box
                  $(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'"/> <a href="#" class="removeclass">Remove</a></div>');
                  x++; //text box increment
      
                  $("#AddMoreFileId").show();
      
                  $('AddMoreFileBox').html("Add field");
      
                  // Delete the "add"-link if there is 3 fields.
                  if(x == 3) {
                      $("#AddMoreFileId").hide();
                      $("#lineBreak").html("<br>");
                  }
              }
              return false;
      });
      
      $("body").on("click",".removeclass", function(e){ //user click on remove text
              if( x > 1 ) {
                      $(this).parent('div').remove(); //remove text box
                      x--; //decrement textbox
      
                      $("#AddMoreFileId").show();
      
                      $("#lineBreak").html("");
      
                      // Adds the "add" link again when a field is removed.
                      $('AddMoreFileBox').html("Add field");
              }
          return false;
      }) 
      
      });
      

      【讨论】:

        【解决方案7】:

        为什么不删除行中的.after()

        newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
        

        到

        newTextBoxDiv.html('<label>Textbox #'+ counter + ' : </label>' +
        

        【讨论】:

          【解决方案8】:

          在你的点击函数中,你可以写:

          function addMoreRows(frm) {
             rowCount ++;
             var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="" type="text" size="17%"  maxlength="120" /></td><td><input name="" type="text"  maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input name="" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> <a href="javascript:void(0);" onclick="removeRow('+rowCount+');">Delete</a></p>';
             jQuery('#addedRows').append(recRow);
          }
          

          或点击此链接: http://www.discussdesk.com/add-remove-more-rows-dynamically-using-jquery.htm

          【讨论】:

            【解决方案9】:

            另一种解决方案可能是:

            <script>
            $(document)
                    .ready(
                            function() {
                                var wrapper = $(".myFields");
                                $(add_button)
                                        .click(
                                                function(e) {
                                                    e.preventDefault();
                                                    $(wrapper)
                                                            .append(
                                                                    '.....'); //add fields here
                                                });
                                $(wrapper).on("click", ".delFld", function(e) {
                                    e.preventDefault();
                                    $(this).parent('div').remove();
                                })
                            }); 
            </script>
            

            来源:Here

            【讨论】:

              【解决方案10】:

              你也可以使用类似的东西

              <!DOCTYPE html>
              <html lang="en">
              <head>
              <meta charset="utf-8">
              <title>jQuery Add / Remove Table Rows Dynamically</title>
              <style type="text/css">
                  form{
                      margin: 20px 0;
                  }
                  form input, button{
                      padding: 5px;
                  }
                  table{
                      width: 100%;
                      margin-bottom: 20px;
                      border-collapse: collapse;
                  }
                  table, th, td{
                      border: 1px solid #cdcdcd;
                  }
                  table th, table td{
                      padding: 10px;
                      text-align: left;
                  }
              </style>
              <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
              <script type="text/javascript">
                  $(document).ready(function(){
                      $(".add-row").click(function(){
                          var name = $("#name").val();
                          var email = $("#email").val();
                          var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
                          $("table tbody").append(markup);
                      });
              
                      // Find and remove selected table rows
                      $(".delete-row").click(function(){
                          $("table tbody").find('input[name="record"]').each(function(){
                              if($(this).is(":checked")){
                                  $(this).parents("tr").remove();
                              }
                          });
                      });
                  });    
              </script>
              </head>
              <body>
                  <form>
                      <input type="text" id="name" placeholder="Name">
                      <input type="text" id="email" placeholder="Email Address">
                      <input type="button" class="add-row" value="Add Row">
                  </form>
                  <table>
                      <thead>
                          <tr>
                              <th>Select</th>
                              <th>Name</th>
                              <th>Email</th>
                          </tr>
                      </thead>
                      <tbody>
                          <tr>
                              <td><input type="checkbox" name="record"></td>
                              <td>Peter Parker</td>
                              <td>peterparker@mail.com</td>
                          </tr>
                      </tbody>
                  </table>
                  <button type="button" class="delete-row">Delete Row</button>
              </body> 
              </html>
              

              【讨论】:

                【解决方案11】:

                您应该能够使用此方法(https://www.adminspress.com/onex/view/uaomui)使用 jquery 动态创建和删除输入字段,甚至可以批量生成输入字段并导出为字符串。

                【讨论】:

                  【解决方案12】:

                  你可以试试这个:

                  <input type="hidden" name="image" id="input-image{{ image_row }}" />
                  
                  inputt= '<input type="hidden" name="product_image' value="somevalue">
                  
                  $("#input-image"+row).remove().append(inputt);
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2018-04-12
                    • 2018-08-08
                    • 2013-04-28
                    • 1970-01-01
                    • 2014-02-12
                    • 2013-10-22
                    相关资源
                    最近更新 更多