Jump to content
Sign in to follow this  
IanArcher

Populating list of Provinces in dropwdown based upon Country selection

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

Share this post


Link to post
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.

Share this post


Link to post
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

Share this post


Link to post
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.

Share this post


Link to post
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

Share this post


Link to post
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");

Share this post


Link to post
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?

Share this post


Link to post
Share on other sites

There is still a line that is removing everything from the region dropdown, look closer at the code.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...