Set Select Option Using Jquery -
i have 3 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 filling country, ajax filling state , city fields, no problems there. have 2 countries in database - india , usa.
if select india, ajax gives state correctly. if reselect option label "country" state , city fields go blank. need jquery code fill default labels , values given above "state" , "city" if no country selected (meaning "country") selected.
this can done via database filling in state , city entries , attaching them country , onload (body or javascript) upload default values. make validation work patchwork , not logical flow. hence requirement of jquery solution.
my jquery code 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({}); }
you have again add blank option select field again if country value 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>'); } });
Comments
Post a Comment