0

I have a select input in which the options are 1-6. Depending on the value of that, the same number of inputs are appended to an empty div with unique Id's as such:

$('#no_of_children').change(function() {
    let inputContainer = $('#children_inputs'); 
    console.log(inputContainer);
    inputContainer.empty();

    let num = $(this).val();
    console.log(num);

    for(let i = 1; i<=num; i++) {
      inputContainer.append("<div class='form-group'><label>Child "+i+". Age: <span id='span_child"+i+"' class='font-weight-bold text-danger'></span></label><input class='form-control' type='date' name='child' id='child"+i+"'></div>");
    }
  });

What I expect to happen afterwards is to be able to use $('#child(n)') to get the the input (n being whatever number 1-6). When I inspect the element I see that the inputs are there with the correct ID, but the jQuery selector cannot find it.

I have also tried:

$('#child1').on('change', function() {
    console.log("changed");
  })

which was recommended when I researched this problem but it does not work for me.

BranOIE
  • 400
  • 4
  • 19
  • If that's your goal it would make far more sense to put a common class on all the dynamic elements instead of having to make repeated `#childN` selectors and attaching the event to them. Regardless of the method you choose, you will need to use a delegated event handler for the dynamic content. See the duplicate for more information – Rory McCrossan Oct 15 '20 at 10:46
  • You need to write function after your dynamic html added to DOM – Prashanth Reddy Oct 15 '20 at 10:46
  • Why not $('#span_child1').on('change', function(){ console.log('1)}) ? – Jakub Ujvvary Oct 15 '20 at 10:48
  • Also You can add class and use class selector to span_child element and then get array of span_child1......span_child6 and iterate trough it – Jakub Ujvvary Oct 15 '20 at 10:48
  • Here's a basic implementation of what I described in my first comment: https://jsfiddle.net/RoryMcCrossan/eLm5x3ps/ – Rory McCrossan Oct 15 '20 at 10:52

0 Answers0