Rishi
Rishi

Reputation: 162

Populate multiple dropdowns with data from ajax

I have a form with multiple dropdown

<select id="0" name ="0">
<option value="abc">ABC</option>
<option value="def">DEF</option>
.
.
.
<option value="mno">MNO</option>
</select>
.
.
.
<select id="9" name="9">
<option value="abc">ABC</option>
<option value="def">DEF</option>
. 
.
.
<option value="mno">MNO</option>
</select>

// This is the basic structure of the code

Now I have a ajax call which gives the following json data

{"2":"abc","5":"def","6":"ghi","7":"def","4":"mno"}

I want to populate the dropdown as per the json data

eg for this case the dropdown with id 2 show have the option value as abc selected, the dropdown with od 5 should have its option with value as def selected and so on.

 $.ajax({
        type : 'POST',
        url : ajax_url,
        data : datavar,

        success : function(msg) {

        }
        });

The json data is present in the msg parameter of success.

How should I proceed?

Upvotes: 2

Views: 211

Answers (2)

Brand
Brand

Reputation: 107

Or do it like this if you want to keep it all jquery :)

$.ajax({
    type : 'POST',
    url : ajax_url,
    data : datavar,

    success : function(msg) {
      $.each(msg, function(k, v){
         $('#'+k).val(v);
      });
    }
});

This will loop through each of the returned objects properties and use the k (key) to find the select and assign the selected value (v).

And you can also do it like this:

for(var key in msg){
    if(msg.hasOwnProperty(key)){
        $('#'+key).val(msg[key]);
    }
}

You'll just need to make sure you fix the value attributes of your select boxes. Right now they are missing the trailing value="ABC(") ... that will cause problems

Upvotes: 1

Rottingham
Rottingham

Reputation: 2604

Since you are using AJAX and JQUERY, this is how I would accomplish your feat:

for(var i = 0; i <= msg.length; i+=2) {
    $('#' + msg[i]).val(msg[i+1]);
}

This will take the first item in the JSON data which is the select box ID and set its value to the second piece of JSON data. In affect, its tell the drop box to set SELECTED="SELECTED" on the OPTION that contains that value.

Sorry if this isn't that clear!

Upvotes: 0

Related Questions