Ratana Ratana - 6 months ago 23
HTML Question

Adding value into textbox subsequently

i am new in Javascript and need some help for a little problem.
i have a button to add textbox value but its value must be sequence number.



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>





how to run subsequently?
if i remove middle of textbox then add new, value run wrong range and duplicate.

Answer

Here this working. I have do it from for loop

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;
}
<!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>