Jump to content

Populating list of Provinces in dropwdown based upon Country selection


IanArcher

Recommended Posts

Hello,I need a some assistance with this javascript/jquery script.I have a page where Every Region/Province/State is a MySQL table called `States`Organization:FgMR4.png There is a dropdown menu called Province, that has all these Regions in it. I'm trying to make it so that when a user selects a country from the Country dropdown menu:

<select add_other="" multiplyable="true" class="form_input_select" name="Country[]">

The Province drop-down menu below it runs a query to show all States/Provinces that belong to the Country selected and filters/strips out the others that don't.

<select add_other="" multiplyable="true" class="form_input_select" name="Province[]"><option value="204">Alsace</option><option value="239">Aquitaine</option><option value="271">Auvergne</option>

The SQL Query that could work for this SELECT * FROM `States` WHERE (Selected Country) LIKE 'Country` I've read and looked around and apparently the only effective way to do this with Javascript/JSON to use it with PHP as you can only use node.js to connect to a MySQL database.I'm fairly new to Javascript and really need some pointing in the right direction to put this together as most of the scripts I've found around are really specific to their needs for their site.I'm doing this on Boonex Dolphin so not much modifying the hardcoded HTML itself, which is why I have to take the Javascript/Jquery route with this. Thanks in advance

Link to comment
Share on other sites

Your options are to either use PHP to print out Javascript arrays that hold all of the options that you can look up when one of them changes, or use ajax to send a request to get the options on demand. If you haven't looked into ajax then start with that, you just need to send the selected value in an ajax request, have PHP respond with the options that match it (it's probably easiest to have it output a JSON-encoded array of options), and then loop through the options and add each one to the select element. Each of those is a different piece, so concentrate on one piece at a time until they work and you can combine them.

Link to comment
Share on other sites

Thanks for the response, there is an existing code for this on the site i'm doing it for, i was just thinking of reinventing it. Here it is, i've highlighted the part i'm referring to:

	<script type="text/javascript">		var oBxUserStatus = new BxUserStatus();		oBxUserStatus.userStatusInit('<bx_url_root />', __is_profile_page__);		/**		*	Zehair :  		*/		$(document).ready(function()		{ /*** Region Code Starts Here ***/		  $('.form_input_select[name="REGION[]"]').html('');			$('.form_input_select option[value=""]').attr("selected","selected");			$('.form_input_select[name="Country[]"]').live('change', function(e)			{				var pay = $(this).val();				$.get('/m/events/home/?ajax=state&country='+pay, {}, function(r)				{					$('.form_input_select[name="REGION[]"]').html(r);				});			});						$('.form_input_select[name="REGION[0]"]').html('');			$('.form_input_select option[value=""]').attr("selected","selected");			$('.form_input_select[name="Country[0]"]').live('change', function(e)			{				var pay = $(this).val();				$.get('/m/events/home/?ajax=state&country='+pay, {}, function(r)				{					$('.form_input_select[name="REGION[0]"]').html(r);				});			}); /*** Region Code Ends Here ***/  			if(window.location.pathname == '/index.php' || window.location.pathname == '/' )			{				$('.mainLogo').css("margin-left","-3px");			}			$('.topMenu td:last-child').remove();			$('input[name=copy_to_profile_photos]').attr('checked', false);			// $('input[name=copy_to_profile_photos]').hide();			// $('label[for=copy_to_profile_photos]').hide();									$(".form_input_submit img").each(function (i)			{				$(this).filter(function()				{					return (($(this).attr('alt') == 'Personnaliser ' ) ? true : false );				}).parent().parent().parent().parent().hide();			});							$(".form_input_submit img").each(function (i)			{				$(this).filter(function()				{					return (($(this).attr('alt') == 'Ajouter son' ) ? true : false );				}).parent().parent().parent().parent().hide();			});			$(".form_input_submit img").each(function (i)			{				$(this).filter(function()				{					return (($(this).attr('alt') == 'Ajouter des vidéos' ) ? true : false );				}).parent().parent().parent().parent().hide();			});				$(".form_input_submit img").each(function (i)			{											$(this).filter(function()				{					return (($(this).attr('alt') == "Demander une info" ) ? true : false );				}).parent().parent().parent().parent().hide();	 							});	  			$('.subMenuInfoKeeper .thumbnail_block').hide()		});	</script>	

By default there is a field called Region, and it's populating from a table in the database. The issue is whatever value is stored for that user for this field is being cloaked by a blank option value. I still want the code to be intact for when the Country is changed, but to populate with the user's region by default. Like uncloacking it, until it's changed. I attempted to comment out the lines of code where the option[value=""], but it did nothing. Any ideas?

Edited by IanArcher
Link to comment
Share on other sites

Is the issue that you're trying to load the form and have certain things pre-selected? That wouldn't be part of Javascript (unless Javascript has those values), normally you would just use PHP to write out the list of options and indicate which one is selected. It looks like when that code runs initially it clears out the options in the region dropdown and sets the blank option to be selected, I'm not sure why Javascript would do that. Normally PHP should be responsible for how the page looks initially, I've never used Javascript to initialize a form.

Link to comment
Share on other sites

In essence, PHP is putting out the list of options to the dropdown, but the person before used this javascript code to work with the Country dropdown. Before the Region dropdown was a standalone field filled with options from the database using PHP. And on a slower connection, you can see the pre-populated value that the user has chosen for their region, until the page is finished loading and the Javascript overwrites it to be blank. I only want the javascript to stop doing that until the Country menu is changed. Does that look possible in the code?

Edited by IanArcher
Link to comment
Share on other sites

These lines remove everything from the region item and make any option with a blank value selected: $('.form_input_select[name="REGION[]"]').html('');$('.form_input_select option[value=""]').attr("selected","selected");

Link to comment
Share on other sites

These lines remove everything from the region item and make any option with a blank value selected: $('.form_input_select[name="REGION[]"]').html('');$('.form_input_select option[value=""]').attr("selected","selected");
I commented out those lines of code:
   /*$('.form_input_select[name="REGION[]"]').html('');*/   /*$('.form_input_select option[value=""]').attr("selected","selected");*/   $('.form_input_select[name="Country[]"]').live('change', function(e)   {    var pay = $(this).val();    $.get('/m/events/home/?ajax=state&country='+pay, {}, function(r)    {	 $('.form_input_select[name="REGION[]"]').html(r);    });   });     $('.form_input_select[name="REGION[0]"]').html('');   /*$('.form_input_select option[value=""]').attr("selected","selected");*/   $('.form_input_select[name="Country[0]"]').live('change', function(e)   {    var pay = $(this).val();    $.get('/m/events/home/?ajax=state&country='+pay, {}, function(r)    {	 $('.form_input_select[name="REGION[0]"]').html(r);    });   });

And it prepopulates the entire list of Regions/Provinces for the world and when i change the Country drop-down it filters the Regions/Provinces by Country, which is fine, but when i am editing a user's profile with those two fields, by default the Region field still is blank with no options below it until you change the Country, instead of showing the user's chosen region that's stored in the MySQL database. Any ideas?

Link to comment
Share on other sites

You're right, It's pretty tricky, but I managed to achieve what i wanted with this:

<script type="text/javascript" language="javascript">         window.onload = function()    {        $('.form_input_select[name="Country[]"]').attr("value","PSC");                    /*$('.form_input_select[name="REGION[]"]').html('');*/            /*$('.form_input_select option[value=""]').attr("selected","selected");*/            $('.form_input_select[name="Country[]"]').live('change', function(e)            {                var pay = $(this).val();                $.get('/m/events/home/?ajax=state&country='+pay, {}, function(r)                {                    //$('.form_input_select[name="REGION[]"]').html(r);                });            });                        //$('.form_input_select[name="REGION[0]"]').html('');            /*$('.form_input_select option[value=""]').attr("selected","selected");*/            $('.form_input_select[name="Country[0]"]').live('change', function(e)            {                var pay = $(this).val();                $.get('/m/events/home/?ajax=state&country='+pay, {}, function(r)                {                    $('.form_input_select[name="REGION[0]"]').html(r);                });            });        };</script>

It still doesn't filter if you select the Region dropdown itself, but it comes with the the user's chosen Region, and the Country change event still works.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...