0

I have a dynamic table which contains multiple textboxes. I need textbox B to have a maximum of 6 number input and will prompt an error if the input value is less than and not equal to 6. Please help Im new to javascript

function addRow() {
  var table = document.getElementById("bod");
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);


  row.insertCell(0).innerHTML = '<input type="text" name="A" size="20" maxlength="6" required/>';
  row.insertCell(1).innerHTML = '<input type="text" name="B" size="20" required/>';
  row.insertCell(2).innerHTML = '<input type="text" name="C" size="20" required/>';

}
<input type="button" id="add" value="Add" onclick="Javascript:addRow()">
<table id="bod">
  <tr>
    <th>A</th>
    <th>B</th>
    <th>C</th>
  </tr>
</table>
etarhan
  • 4,138
  • 2
  • 15
  • 29
Blue Minnie
  • 231
  • 1
  • 12
  • 1
    Have a look at this post (https://stackoverflow.com/a/10294291/10353987). It outlines how you can use a pattern if you need a bit more complex validation for your input – etarhan Apr 04 '19 at 00:27

1 Answers1

0

Create input manually and addEventListener to it. Something like this.

function addRow() {
  var table = document.getElementById("bod");
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  row.insertCell(0).innerHTML = '<input type="text" name="A" size="20" maxlength="6" required/>';
  var colB = row.insertCell(1);
  var inp = document.createElement('input');
  inp.type = 'text';
  inp.name = 'B';
  inp.size = 20;
  inp.required = true;
  colB.appendChild(inp);
  inp.addEventListener('change', function() {
    if (this.value.length !== 6) {
      alert('wrong value');
      this.focus();
    }
  });
  row.insertCell(2).innerHTML = '<input type="text" name="C" size="20" required/>';

}
<input type="button" id="add" value="Add" onclick="addRow()">
<table id="bod">
  <tr>
    <th>A</th>
    <th>B</th>
    <th>C</th>
  </tr>
</table>
Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36