随后在文本框中添加值

时间:2016-06-05 13:29:47

标签: javascript html

我是Javascript的新手,需要一些帮助来解决一个小问题。 我有一个按钮来添加文本框值,但其值必须是序列号。

var i = 1;

function AddNew() {
  if (i <= 3) { //if you don't want limit, you remove IF condition
    i++;
    var div = document.createElement('div');
    div.innerHTML = '<input type="text" name="lineitem_' + i + '" value="' + i + '" maxlength="2" size="2"> <input type="text" name="materialcode_' + i + '" placeholder="Material Code" maxlength="18" size="18"><input type="button" onclick="removeItm(this)" value="-">';
    document.getElementById('addingitem').appendChild(div);
  }
}

function removeItm(div) {
  document.getElementById('addingitem').removeChild(div.parentNode);
  i--;
}
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Untitled Document</title>
</head>

<body>
  <form action="testing.php" method="post">
    <div id="addingitem">
      <input type="text" name="lineitem_1" id="item" value="1" maxlength="2" size="2">
      <input type="text" name="materialcode_1" placeholder="Material Code" maxlength="18" size="18">
      <input type="button" name="addnew" id="Add_New()" onClick="AddNew()" value="New Item">
    </div>
  </form>
</body>

</html>

如何随后运行? 如果我删除文本框的中间,然后添加新的,值运行错误的范围和重复。

1 个答案:

答案 0 :(得分:0)

这里有效。我是从var vals = []; $("input[name='item_item_quantity[]']").each(function() { vals.push($( this ).val()); });

开始的

&#13;
&#13;
for loop
&#13;
var i = 1;

function AddNew() {
  if (i <= 3) { //if you don't want limit, you remove IF condition
    i++;
    var div = document.createElement('div');
    div.innerHTML = '<input type="text" name="lineitem_' + i + '" value="' + i + '" maxlength="2" size="2"> <input type="text" name="materialcode_' + i + '" placeholder="Material Code" maxlength="18" size="18"><input type="button" onclick="removeItm(this)" value="-">';
    document.getElementById('addingitem').appendChild(div);
  }
}

function removeItm(div) {
  
  i--;
  
  var addingitem = document.getElementById('addingitem');
  
  addingitem.removeChild(div.parentNode);

  var inputs = addingitem.querySelectorAll('[name^="lineitem_"]');

  for (var r = 0; r < inputs.length; r++) {
    var item = inputs[r];
    item.value = r + 1;
  }
  
  inputs = null;
}
&#13;
&#13;
&#13;