Sureshkumar Natarajan
Sureshkumar Natarajan

Reputation: 538

jQuery: Why does .change() not trigger an event

I am putting some content read through ajax in a div. The content has certain script tags which are used to bind some events on some element contained in the ajax content.
Ajax Content:

<div>
    <div>
        <select id='mySelectBox'>
            <option value="1">ONE</option>
            <option value="2" selected="selected">TWO</option>
        </select>
    </div>
    <script type="text/javascript">
         $(document).on("change",'#mySelectBox',function(){
            alert($('#mySelectBox').val());
         }); 
        $('#mySelectBox).change(); //problem here....
        </script>
</div>

The change event is bind and working correctly when i change the value of '#mySelectBox'. But here in $('#mySelectBox).change(); statement which triggers the change event immediately after it is bind is not getting called.

what might be the problem.?

Upvotes: 1

Views: 4616

Answers (2)

Michael Richardson
Michael Richardson

Reputation: 4282

I believe you are missing a closing quote. Try this instead:

$('#mySelectBox').change();

Upvotes: 4

Gung Foo
Gung Foo

Reputation: 13568

$('#mySelectBox).change(); does not trigger the event.

$('#mySelectBox).trigger('change'); does. :)

.change() actually is a wrapper for .on('change');

UPDATE:

In case of a delegated event the .trigger() function won't bubble up. A workaround can be found here:

How do I manually trigger a delegated event with jQuery?

Upvotes: 0

Related Questions