1

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
1

1 Answer 1

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.