I have a php function that list all of the countries from my database as a select option, then based on what the user selects for their country im using jquery to make an ajax call and get all of the states/regions for that country. This part works fine. I'm running into an issues, as when a user login's in to edit their profile, how would I make the select change based on what is in the databse.

This makes the options.

<select name='country' id='country'>
  <? getCountry($c['country']); ?>
</select>

Then this is the jquery

$("#country").change(function() {
		var ctry = $(this).val();
		$.get("core/ajax/states.php", {
			country: ctry
		}, function(data) {
			var opt = '';
			if (!data) {} else {
				$.each(data, function(n, val) {
					if(!n){} else{
						opt += '<option value="' + val.code + '">' + val.name + '</option>';
					}
				});
				$("#state").html(opt);
				

			}
		}, 'json');
	});
	
	$("#country").change();

Any help on this matter would be great.

Thanks for your time
-BaSk

The traditional/safe way to do this is by using good old steam-age HTML; no need for any javascript.

Exercise your php skills to build the select menus with the attribute selected="selected" for the required option.

For example, for a user whose profile says "Canada":

<select name="country" id="country">
  <option value="">Select Country</option>
  <option value="Algeria">Algeria</option>
  <option value="Belgium">Belgium</option>
  <option value="Canada" selected="selected">Canada</option>
  <option value="England">England</option>
  <option value="France">France</option>
  <option value="Germany">Germany</option>
</select>

This will work for all users, even those with javascript turned off.

If this is an exercise in jquery, then again you have to exercise your php skills but this time to build a jquery statement and the menu (with no selected attribute):

$(document).ready(function(){
  $("country").val("Canada");
});
<select name="country" id="country">
  <option value="">Select Country</option>
  <option value="Algeria">Algeria</option>
  <option value="Belgium">Belgium</option>
  <option value="Canada">Canada</option>
  <option value="England">England</option>
  <option value="France">France</option>
  <option value="Germany">Germany</option>
</select>

This won't work for users with javascript turned off, which is why it's not normally done this way.

Airshow

post your definition of getCountry($c) function here...

$(document).ready(function(){
  $("country").val("Canada");
});

Sorry, that should be:

$(document).ready(function(){
  $("#country").val("Canada");
});

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.