输入数字以添加更多输入JQuery

时间:2011-03-16 15:22:49

标签: jquery input add

我想要一个表单输入,输入一个数字然后单击它旁边的按钮,这样就可以“添加”前一个输入数量,每个输入都有自己的名字。

  1. 输入数字
  2. 点击Go Button或其他
  3. 在输入数量(创建新输入)的同一页面上输出
  4. 我试过这个,一次只给出一个ADD功能:

    $(function() {
        var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work
    
        $('a#add').click(function() { // when you click the add link
            $('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
    // if you have the input inside a form, change body to form in the appendTo
            i++; //after the click i will be i = 3 if you click again i will be i = 4
        });
    
        $('a#remove').click(function() { // similar to the previous, when you click remove link
        if(i > 1) { // if you have at least 1 input on the form
            $('input:last').remove(); //remove the last input
            i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
        }
        });
    
        $('a.reset').click(function() {
        while(i > 2) { // while you have more than 1 input on the page
            $('input:last').remove(); // remove inputs
            i--;
        }
        });
    
    }); 
    
    <a href="#" id="add">Add</a>  
    <a href="#" id="remove">Remove</a>  
    <input type="text" value="1" />
    

3 个答案:

答案 0 :(得分:2)

这样的东西?

<script>
  $(document).ready(function(){
    $('#addButton').click(function(){
      var count = parseInt($('#quantity').val());
      var newHTML = [];
      for(var i=0;i<count;i++){
        newHTML.push('<input type="text"/><br/>');//or whatever content you want
      }
      $('#sandbox').html(newHTML.join(''));
    });
  });
</script>



<input type="text" id="quantity" value=""/>
<input type="button" id="addButton" value="Add"/>
<div id="sandbox"></div>

答案 1 :(得分:1)

您可以执行以下操作(根据您的需要调整此代码):

var newInputs = parseInt($('#newInputs').val(), 10);
for(var i = 0; i < newInputs; i++){
  var $input = $('<input/>').attr({
    name: 'input_'+i,
    value: i
  }).appendTo('#form');
}

基本上,当您单击“开始”按钮时,您想要获取输入的值,并循环多次。每次迭代,创建一个新的input元素并将其附加到原始表单。

答案 2 :(得分:0)

派对迟到了,但是一个很好的选择是使用jQuery模板$.tmpl(假设你不反对使用插件)

var markup = '<input type="text" id="Input${this.data}" value="" class="auto"/>';
$.template("inputTemplate", markup);

$("input.add").click(function() {
    var times = parseInt($("input.times").val(), 10);
    var total = $("input.auto").length;
    for (var x = 0; x < times; x++) {
        $.tmpl("inputTemplate", (x+ total) ).appendTo("body");
    }
});
$("input.remove").click(function() {
    $("input.auto:last").remove();
});
$("input.reset").click(function() {
    $("input.auto").remove();
});

jsfiddle上的代码示例。