jureispro
jureispro

Reputation: 1402

jQuery fails to change value of SELECT element

I have strange problem with jquery. I want to change data of select element but for some reason it won't change it. Does someone knows why it won't change?

Here is code:

function getData(){
    //$(document).ready(function() {
    $.ajax({
            url: "php/formData.php",
            success: function(data) {
                try {

                    var parsed = JSON.parse(data);
                    $(document).ready(function() {
                    $("#DATA0").val(parsed.name);
                });


                } catch(e) {
                    alert("Error: " + data);
                }
            },
            error: function(data) {
                bootbox.alert("Error: " + data.statusText);
            }
        });

}

HTML:

<select id="DATA0" class="form-control">
<option value="X"></option>
<option value="Data1">Some data</option>
<option value="Data 2">Some data</option>
</select>

Upvotes: 0

Views: 62

Answers (3)

I think you have called function getdata() before the page achieves its ready state so by that when the ajax get into its success function, it doesn't have #DATA0 tag id. So for this you can use following code:

function getData(){
$.ajax({
        url: "php/formData.php",
        success: function(data) {
            try {

                var parsed = JSON.parse(data);
                $("#DATA0 option[value="+parsed.name+"] ").prop("selected",true);


            } catch(e) {
                alert("Error: " + data);
            }
        },
        error: function(data) {
            bootbox.alert("Error: " + data.statusText);
        }
    });
}

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

Your code is not getting called as document is already loaded.You do not need to wrap the code in dom ready. simply use:

$("#DATA0").val(parsed.name);

Demo

Upvotes: 1

Jeff Mahoney
Jeff Mahoney

Reputation: 231

Have you tried (temporarily) creating another element and seeing if you have populate it with the value of parsed.name? I ask because it looks like if you get a value like "KKKK" or something like that it doesn't match any of the options in your select statement - so I'm not sure anything would change. (Because none of the existing items have a value that matches what you got back from your ajax call.)

If, on the other hand, you created a text box (with an ID of "mytextbox"), you try something like this:

$('#mytextbox').val(parsed.name);

Upvotes: 0

Related Questions