-1

What I try to do is to bind an onchange event to an element which is not appended. But this is what I tried:

  var $container = rule.$el.find('.rule-value-container');
  var html = `<input class="form-control" type="number" name="${ name }_0" step="any" min="0">`;

  console.log($(html));
  $(html).on('change', function(e) {
    console.log('test', e);
  })

  $container.html('');
  $container.append(html);
}

But this is not working how can I bind an on change event to an element which is not appended yet?

Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
Sireini
  • 3,872
  • 10
  • 48
  • 84

1 Answers1

3

You need to store the jQuery object directly in your variable and attach the event handler to it, not to the HTML :

var $container = $('.test');
let input = $(`<input class="form-control" type="number" name="test" step="any" min="0">`);

input.on('change', function(e){
    console.log('test');
});

$container.html('');
$container.append(input);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
Zenoo
  • 12,242
  • 4
  • 44
  • 63