using .on to listen for event not working

57 Views Asked by At

I am trying to use .on to listen for an event.

html:

<div class="form-group" id="group_names">
   <label> Names: </label><br>
   <input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>

JS:

for (n = 1; n < inputLength+3 ; ++n) {
     var test2 = document.getElementById(dude+n);
     $(test2).on('change', '#group_names', forFunction);
}

The change to the input field is not being recognized.

Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:

var dude = "name";

function forFunction() {
    for (m = 1; m < inputLength + 1; ++m) {
        var test = document.getElementById(dude + m)
        if (test.value != "") {
            var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";

            document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
            //function updateHTML(txt)
        }
    }
}

I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.

Thanks

2

There are 2 best solutions below

0
On

You probably want to use event delegation on the parent div instead.

$('#group_names').on('change', 'input.form-control.name', forFunction);
0
On

Consider the following jQuery code.

$(function() {
  var inputFields = $("input[id*='name']");

  function forFunction(evt) {
    console.log(evt.type);
    inputFields.each(function(i, el) {
      var n = i + 1;
      if ($(el).val() != "") {
        console.log("Value Detected");
        $("<input>", {
          type: "text",
          class: "form-control name",
          placeholder: "group" + n,
          id: "group" + n,
          name: "group" + n
        }).insertBefore("#group_names");
      }
    });
  }

  inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
  <label> Names: </label><br>
  <input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>

This should work for all of the Input items.