I can successfully bind an event to dynamically added elements, but I have a problem triggering it on its first load programmatically.
$('body').on('change', '#elem', function () {
console.log('bind event success');
});
I tried these codes below but do not work.
Not working
$('body').trigger('change');
Not working
$('body').on('change', '#elem', function () {
console.log('hello world');
}).change();
asked May 31, 2021 at 6:09
-
$('#elem').trigger("change")Swati– Swati2021年05月31日 06:18:51 +00:00Commented May 31, 2021 at 6:18
1 Answer 1
You can trigger an event on the DOM element #elem
directly, as you can see here:
$('body').on('change', '#elem', function () {
console.log('new value is: '+this.value);
});
$("button").click(function(){$("#elem").val("3").change()})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="elem"><option>1</option><option>2</option><option>3</option></select>
<button>trigger change to 3</button>
answered May 31, 2021 at 6:58
Comments
lang-js