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();
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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.