set select option from json

I have function to call json value Now when user opens account edit page I would need the country to be selected by default when the page opens

var url_country="<?=base_url()?>country.json";
 var negara_list ="<option value=''></option>";
    $.getJSON(url_country, function(data) {
      $.each(data,function(key,val){
         negara_list += "<option value="+val+">"+val+"</option>";
      });
      $(".negara").html(negara_list);
  });

Upvotes: 0

Views: 68

Answers (2)

Ashok Sri
Ashok Sri

Reputation: 326

You can try something like this, if your json response is only one country then, No need to play each function, if your response more than one country then you would specify which country is going selected as default

For response with single country

    var url_country="<?=base_url()?>country.json";
    var negara_list ="<option value=''></option>";

    negara_list += "<option value="+url_country.country+" selected>"+url_country.country+"</option>";

       $(".negara").html(negara_list);
    });

For response with mutiple countries

    var my_country = "United States"; // country which is going to auto selected

    var url_country="<?=base_url()?>country.json";

    var negara_list ="<option value=''></option>";

     $.getJSON(url_country, function(data) {

       $.each(data,function(key,val){

          if(my_country == val)
          {
              negara_list += "<option value="+val+" selected>"+val+"</option>";
          }
          else
          {
               negara_list += "<option value="+val+">"+val+"</option>"; 
           }

         });

       $(".negara").html(negara_list);
    });

Upvotes: 0

M.Hemant
M.Hemant

Reputation: 2355

Try this, hope this will help you

var url_country="<?=base_url()?>country.json";
var user_define_country = 'USA';
var negara_list ="<option value=''></option>";
    $.getJSON(url_country, function(data) {
      $.each(data,function(key,val){
         if(user_define_country == val){
            negara_list += "<option value="+val+" selected='selected'>"+val+"</option>";
         }else{
            negara_list += "<option value="+val+">"+val+"</option>";
         }
      });
      $(".negara").html(negara_list);
  });

Upvotes: 2

Related Questions