DragonFire DragonFire - 3 months ago 8
jQuery Question

Set Select Option Using Jquery

I have three select boxes of Country, State, City

<select name="property_country" id="country" >
<option value="">Country</option>
</select>

<select name="property_state" id="state" >
<option value="">State</option>
</select>

<select name="property_city" id="city">
<option value="">City</option>
</select>


PHP is filling the country, Ajax is filling the State and City fields, no problems there. I have two countries in the dbase India, USA.

If I select India, ajax gives the state correctly. But if I reselect option label "Country" then state and city fields go blank. I need Jquery to fill the default labels and values as given above "State" and "City" if no country is selected (meaning "Country") is selected.

This can be done via database by filling in State and City entries and attaching them to Country and then onload (body or javascript) upload the default values. But that will make the validation work also patchwork and not a logical flow. Hence the requirement of Jquery solution.

My Jquery Code is below:

$(document).ready(function() {
$('#country').on('change', function() {
var country_id = $('#country').val();
$.ajax({
type: 'POST',
url: '../controllers/select.php',
data: "country_id=" + country_id,
success: function(msg) {
$("#state").html(msg);
}
});
});

$('#state').on('change', function() {
var state_id = $('#state').val();
$.ajax({
type: 'POST',
url: '../controllers/select.php',
data: "state_id=" + state_id,
success: function(msg) {

$("#city").html(msg);
}
});
});


I tried

if (country_id == "")
{
$("#state").val("State");
}
else
{

$.ajax({
});
}

Answer

You have to again add the blank option the select field again if country value is reset.

$('#country').on('change', function() {
var country_id = $('#country').val();
if(country_id){
  $.ajax({
    type: 'POST',
    url: '../controllers/select.php',
    data: "country_id=" + country_id,
    success: function(msg) {
      $("#state").html(msg);
    }
   });
  }
  else{
    $("#state").html(' <option value="">State</option>'); 
    $("#city").html(' <option value="">City</option>'); 
  }
});