Brian Schroeter
Brian Schroeter

Reputation: 1633

jQuery -- Unable to change value of select box populated with AJAX

Our website's page can be seen here and the problem is related to the Year, Make, Model widget at the top of the content area. When a year, make, model, submodel, and engine is chosen... Part Type is the next drop-down and it's values (like the others) are populated via AJAX. Unfortunately, I'm trying to set this value based on the category the person is on and will actually be hiding the field completely.

I'm using the code below to attempt this --

jQuery('div.amfinder-horizontal td:nth-child(5) select').change(function () {
    jQuery("div.amfinder-horizontal td:nth-child(7) select").append('<option value="0">Position</option>');
    jQuery(this).parent().addClass('active');
    jQuery(".popover").hide();
    jQuery("#popover6").show();
    jQuery("div.amfinder-horizontal td:nth-child(6) select option").each(function() { this.selected = (this.text == "Windshield Wiper Blade"); });
    jQuery("div.amfinder-horizontal td:nth-child(6) select option").change();
    // The following two lines are commands for a Prototype script, in place to simulate the change event
    $('finder-4023--20454').simulate('click'); // This is the ID of the select element ( it is the same as div.amfinder-horizontal td:nth-child(6) select )
    $('finder-4023--20454').simulate('change'); // This is the ID of the select element ( it is the same as div.amfinder-horizontal td:nth-child(6) select )
    console.log('Changed!');
});

I believe what is happening is that the AJAX population occurs and then the change event tries to trigger before the AJAX function finishes. The AJAX is in a Prototype script and I'm not comfortable changing that. Instead, I'm wondering if I could simply delay the change and simulate events for a second or so that the AJAX population can finish.

Please help out. :-)

Upvotes: 2

Views: 256

Answers (1)

Shomz
Shomz

Reputation: 37701

Try replacing the first line with this:

jQuery(document).on('change', 'div.amfinder-horizontal td:nth-child(5) select',function () {

This will work for the elements that are added even after the code was called, which is something you must have when you render parts of the page with AJAX.

Read about delegated events here: http://api.jquery.com/on/

Upvotes: 1

Related Questions