Nathan Gilford Nathan Gilford - 6 months ago 10
Javascript Question

Set option selected with jQuery

I have a situation where I need to use jQuery to initialize a selected option within a select (United States within the Country dropdown). Unfortunately I can't set it within the HTML due to limitations of the platform, and there aren't any classes or ids to target. This form also changes based on ajax (there are 3 versions of the same form based on whether the person is a guest, registering while checking out, or is already registered). The current script I've created works, but won't let you change to another country:

$(document).ajaxSuccess( function() {
$('option:contains("United States"):not(:contains("Minor"))').prop("selected", true);
});


So basically while it sets it as selected, it does not allow the user to change from the United States options. It appears the Ajax might be reloading every time an option is set for what ever reason.

Thanks!

Answer

So, based on the comments it seems that every time you try to change the dropdown, more AJAX is called. In turn, this calls your $.ajaxSuccess function. This means it gets reset on every single AJAX call!

You could do something like this:

var set = false;
$(document).ajaxSuccess( function() {
   if (set) return;
   $('option:contains("United States"):not(:contains("Minor"))').prop("selected", true);
   set = true;
});

Or, you could take advantage of the arguments passed to ajaxSuccess to determine if the code should even be run. For example:

$(document).ajaxSuccess( function(event, xhr, options) {
   if (xhr.url !== 'the url im listening for') return;
   $('option:contains("United States"):not(:contains("Minor"))').prop("selected", true);
});

That approach will only work if there is one particular URL you are listening for of course, but you get the idea. Just make sure that ajaxSuccess function only when it is needed to be.