更好地动态添加和删除字段的方法是什么?

时间:2015-09-03 16:14:39

标签: javascript jquery

我设法使用input[type"number"]添加和删除字段。我使用jquery来做这个,但我做的方式并不完美。如果该字段中有值,则如果由于使用.remove()而更改了数值,则该值将被删除。有没有更好的方法来做到这一点?

<body>
    <input type="number" id="num" min="0" max="20" required/>
    <div class="dynamicInput"></div>
</body>

<script>
    $('#num').bind('keyup mouseup', function () {
        $('.dynamicInput .row').remove();
        $('.dynamicInput h4').remove();
        if ($(this).val() > 0) {
            $('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
            var num = $(this).val();
            for (var i = 0; i < num; i++) {
                $('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
            }
        }
    });
</script>

My Fiddle

6 个答案:

答案 0 :(得分:2)

尝试这样的事情。不是每次都删除所有输入,而是删除最后的输入,或者在末尾添加更多输入。

这个与你的主要区别在于我添加了var totNum = 0;来跟踪当前的输入数量。然后我用它来确定添加/删除的数量。

var totNum = 0;
$(document).on('keyup mouseup', '#num', function(){
  var num = $(this).val();
  if (num != "")
  {
    if (totNum == 0)
       $('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
    for (var i = num; i < totNum; i++)
    {
       $('.dynamicInput .row:last-child').remove();
    }
    for (var i = totNum; i < num; i++)
    {
       $('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
    }
    totNum = num;

    if (totNum == 0)
    {
       $('.dynamicInput h4').remove();
       $('.dynamicInput .row').remove();
    }
  }
});
input[type="number"] {
  width: 200px;
  height: 30px;
  font-family: Arial, sans-serif;
  font-size: 20px;
}
.row {
  display: block;
  margin-bottom: 15px;
}
body {
  width: 100%;
  padding: 40px;
}
input[type="text"] {
  width: 100%;
}
.col1,
.col2 {
  width: 45%;
  display: inline-block;
  margin-right: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<body>
  <input type="number" id="num" min="0" max="20" required/>
  <div class="dynamicInput"></div>
</body>

答案 1 :(得分:2)

使用数据结构作为您可以构建视图的骨架,它更容易失败并且不太可能失败。请注意,此技术需要额外的计算以节省用户输入,这就是为什么我添加了&#34;更改&#34;事件

在下面的代码片段中,我并排制作了两个面板。左边是一个输入列表,非常接近你的输入,很容易适应你的需要,而正确的输入允许看到数据的演变&#34;根据用户操作的数组。

两个小组都依赖于&#34;数据&#34;换句话说,只要新项目被添加到数据&#34;数据&#34;或更新单个项目,就会完全重建这两个面板。请注意,&#34;更改&#34;事件利用事件委托来处理新添加的输入。

最后,&#34;更新&#34;当相应的输入改变时,函数更新整个数据源或数据源的单个项,而#34;渲染&#34;函数在数据源上绘制,以使面板与数据保持同步。顺便说一下,右面板在开始时渲染一次。

&#13;
&#13;
$(function () {

  var data = []; // data source
  var $num = $('#num'); // input for number of rows
  var $left = $('#left'); // left panel
  var $right = $('#right'); // right panel
  
  // render the right panel at starting

  renderRightPanel();

  // when the number of rows changes:
  //  - rebuild the left panel entirely
  //  - keep the data list up to date
  //  - print the array to the right panel

  $num.on('keyup mouseup', function () {
    renderLeftPanel($(this).val());
    updateList();
    renderRightPanel();
  });

  // when a value changes:
  //  - keep the data item up to date
  //  - print the array to the right panel

  $left.on('change', 'input', function () {
    var i = $left.find('input').index(this);
    updateItem(i, $(this).val());
    renderRightPanel();
  });

  // updates the data list

  function updateList () {
    data = $left.find('input').map(function () {
      return $(this).val();
    }).get();
  }

  // updates a single data item

  function updateItem (index, value) {
    data[index] = value;
  }

  // refreshes the DOM of the right panel

  function renderRightPanel () {
    $right.html('<pre>data = ' + (
      JSON.stringify(data, 0, 4)
    ) + '</pre>');
  }

  // refreshes the DOM of the left panel

  function renderLeftPanel (nLines) {
    var i;
    var html = '';
    if (nLines > 0) {
      html = '<h4>Heading</h4>';
      for (i = 0; i < nLines; i++) {
        html += '<div><input value="' + (data[i] || '') + '" /></div>';
      }
    }
    $left.html(html);
  }
});
&#13;
body * {
  padding: 0;
  margin: 0;
}

h4, input {
  margin-bottom: .5em;
}

#panels {
  border: 1px solid black;
}

#panels > div {
  display: table-cell;
  padding: 1em;
}

#right {
  border-left: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panels">
  <div id="left"></div
  ><div id="right"></div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

禁用并隐藏额外元素,而不是删除它们。这将阻止它们被发布,并且还保留已输入的所有值的先前值。见fiddle

最后一点,如果您不想保留隐藏元素的值,请将.hide()更改为.hide().val("")

<body>
    <input type="number" id="num" min="0" max="20" required/>
    <div class="dynamicInput">
        <h4>Please fill in the name and email of each extra attendees</h4>
    </div>
</body>

<style>
    .col1, .col2 { display: inline; width: 48%; margin-right: 2%; }
    .row { padding: 5px; }
</style>

<script>
    for (var i = 0; i < 20; i++) {
        $('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
    }
    $('#num').bind('keyup mouseup', function () {
        var num = parseInt($(this).val());
        $('.dynamicInput .row')
            .slice(num)
            .hide()
            .attr('disabled','disabled');
        if ( num > 0) {
            $('.dynamicInput .row')
                 .slice(0,num).show()
                 .removeAttr('disabled');
            $('.dynamicInput h4').show();
        } else {
            $('.dynamicInput h4').hide();
        }
    }).trigger('keyup');
</script>

答案 3 :(得分:0)

副手,你可以在javascript中缓存这些值,以防止在#num更改之间丢失它们。 e.g。

(function($){
  var $num = $('#num'),
      $dynamic = $('.dynamicInput');
      cache = {};
  
  $dynamic.on('change', 'input', function(e){
    cache[$(this).prop('name')] = $(this).val();
  });
  
  $num.on('change keyup mouseup', function(e){
    $dynamic.empty();
    
    var val = parseInt($(this).val(), 10);
    if (!isNaN(val) && val > 0){
      $('<h4>')
        .text('Please fill in the name and email of each extra attendees')
        .appendTo($dynamic);
      for (var i = 0; i < val; i++){
        
        var nameName = 'attendeesName' + i,
            emailName = 'attendeesEmail' + i;
        
        var $row = $('<div>',{'class':'row'}),
            $col1 = $('<div>',{'class':'col1'}).appendTo($row),
            $col2 = $('<div>',{'class':'col2'}).appendTo($row);
        
        $('<input>',{
          'type': 'text',
          'name': nameName,
          'placeholder': 'Name',
          'required': 'true'
        }).val(cache[nameName] || '').appendTo($col1);
        $('<input>',{
          'type': 'email',
          'name': emailName,
          'placeholder': 'Email',
          'required': 'true'
        }).val(cache[emailName] || '').appendTo($col2);
        
        $row.appendTo($dynamic);
      }
    }
  });
  
})(jQuery);
input[type="number"] {
    width:200px;
    height:30px;
    font-family:Arial, sans-serif;
    font-size:20px;
}
.row {
    display:block;
    margin-bottom:15px;
}
body{
    width:100%;
    padding:40px;
}
input[type="text"]{
    width:100%;
}
.col1, .col2{
    width:45%;
    display:inline-block;
    margin-right:10px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>

答案 4 :(得分:0)

以下是尝试改进已接受的答案:

&#13;
&#13;
$(function () {

  var $num = $('#num');
  var $panel = $('#panel');
  var h4 = '<h4>Heading</h4>';
  var row = '<div><input /></div>';

  $num.on('mouseup keyup', function () {
    var n, $inputs;
    var value = $(this).val();
    if (value <= 0) {
      $panel.empty();
    }
    else {
      $inputs = $panel.find('input');
      // get the number of inputs already added
      n = $inputs.size();
      // add your heading if there is no input
      if (n === 0) {
        $panel.append(h4);
      }
      // the user wants less inputs
      if (value < n) {
        $inputs.slice(value).remove();
      }
      // the user wants more inputs
      else if (value > n) {
        $panel.append( 
          // a little trick, see below
          new Array(value - n + 1).join(row)
        );
      }
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panel"></div>
&#13;
&#13;
&#13;

&#34;数组连接技巧&#34;:

var a = [1, 2, 3, 4];
console.log(a.join('+'));
// prints "1+2+3+4"

var b = new Array(4); // an array of 4 undefined items
console.log(b.join('+'));
// prints "+++"

var c = new Array(3);
console.log('<ul>' + c.join('<li>item</li>') + '</ul>');
// prints "<ul><li>item</li><li>item</li></ul>"

答案 5 :(得分:-2)

这正是您正在寻找的,

{{1}}