aneto
aneto

Reputation: 1531

jQuery not change the selected option after load data with Ajax

Why this code:

$('#state option[value=5]').attr('selected', 'selected');

Only work in:

load: function (states) {
            $.each(states, function(key, state) {
                var stateText = state.state + ' (' + state.acronym + ')';
                $('#state').append($('<option />').attr('value', state.id).text(stateText));
                $('#state option[value=5]').attr('selected', 'selected'); // HERE THE CODE WORK
            });

and doesn't work in:

$(function() {
    loadData(state);
    $('#state option[value=5]').attr('selected', 'selected'); // HERE THE CODE DOESN'T WORK
});

See the complete JS file:

var loadData = function(object) {
    $.ajax({
        url: object.url(),
        type: "GET",
        dataType: "json",
        async: "false",
        success: function(data) {
            object.load(data);
        }
    });
};

var state = {
    url: function () {
        return 'resources/js/radio/states/states.json';
    },
    load: function (states) {
        $.each(states, function(key, state) {
            var stateText = state.state + ' (' + state.acronym + ')';
            $('#state').append($('<option />').attr('value', state.id).text(stateText));
            $('#state option[value=5]').attr('selected', 'selected'); // HERE THE CODE WORK
        });
    }
};

$(function() {
    loadData(state);
    $('#state option[value=5]').attr('selected', 'selected'); // HERE THE CODE DOESN'T WORK
});

Upvotes: 1

Views: 3029

Answers (2)

aneto
aneto

Reputation: 1531

The problem is the async process, to fix this it just removed the double quotes:

async: false,

In the original code I used quotes in the code:

async: "false",

Upvotes: 1

albciff
albciff

Reputation: 18507

A possible explanation is that: Your success callback in the ajax call loads the <options> on <select id="state"> through state.load(data) function :

    success: function(data) {
        object.load(data);
    }

Because object.load(data); do the job loading the options: $('#state').append($('<option />').attr('value', state.id).text(stateText));. If the ajax call result on error instead of on success this is never called and the options are never load so then when you call $('#state option[value=5]').attr('selected', 'selected'); after your ajax call the code doesn't work because there is no option to be selected.

Check this out adding error callback to your ajax call:

$.ajax({
    url: object.url(),
    type: "GET", 
    dataType: "json",
    async: "false",
    success: function(data) {
        object.load(data);
    },
    error: function(jqXHR, textStatus, error){
        // console.log or alert... to check if there is an error
    }
});

Hope this helps,

Upvotes: 0

Related Questions