Skip to content Skip to sidebar Skip to footer

Pure Javascript Approach To Adding Value Of Dynamic Input Fields To Array

EDIT Starting with the solution below, I was able to build out the following, which I could use to create timestamps: // Ready the Chunking Function so we can group entries functio

Solution 1:

Try:

var inputs = document.getElementsByName('input_252[]');
var i;
for (i = 0; i < inputs.length; i++) {
   var input = inputs[i];
   // work with input (validate, etc.)
}

Solution 2:

Are you trying to achieve something like this:

Note: For testing purpose, I have used a common regex to accept only alphabets.

JSFiddle

Code

function getRowHTML(id) {
  var HTML = "<div class='row'>" +
    "<input type='text' name='input_252[]' id='" + id + "' />" +
    "<p class='error'></p>" +
    "</div>";

  return HTML;
}

function createHTML() {
  var _html = "";
  for (var i = 0; i < 5;) {
    _html += getRowHTML("txt" + i++);
  }

  document.getElementById("content").innerHTML = _html;
}

function validateInputs() {
  var regex = /^[a-z]+$/gi;

  var inputs = document.getElementsByName("input_252[]");
  Array.prototype.forEach.call(inputs, function(txt) {
    var lblErr = txt.nextSibling;
    lblErr.innerText = regex.test(txt.value) ? "" : "Invalid Value";

  });
}

(function() {
  createHTML();
})()
.row {
  width: 90%;
  padding: 5px;
  margin: 5px;
}
.error {
  color: red;
}
<div id="content"></div>
<button onclick="validateInputs()">Validate</button>

Post a Comment for "Pure Javascript Approach To Adding Value Of Dynamic Input Fields To Array"