dcsimg
www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: CountryTerritory/StateProvinceRegion/CityTownDistrict dropdown list.

  1. #1
    Join Date
    Sep 2015
    Posts
    19

    CountryTerritory/StateProvinceRegion/CityTownDistrict dropdown list.

    I'm using the dropdown list contained in http://www.javascriptsource.com/form...down-list.html

    // State lists
    var states = new Array();

    states['Canada'] = new Array('Alberta','British Columbia','Ontario');
    states['Mexico'] = new Array('Baja California','Chihuahua','Jalisco');
    states['United States'] = new Array('California','Florida','New York');

    // City lists
    var cities = new Array();

    cities['Canada'] = new Array();
    cities['Canada']['Alberta'] = new Array('Edmonton','Calgary');
    cities['Canada']['British Columbia'] = new Array('Victoria','Vancouver');
    cities['Canada']['Ontario'] = new Array('Toronto','Hamilton');

    cities['Mexico'] = new Array();
    cities['Mexico']['Baja California'] = new Array('Tijauna','Mexicali');
    cities['Mexico']['Chihuahua'] = new Array('Ciudad Juárez','Chihuahua');
    cities['Mexico']['Jalisco'] = new Array('Guadalajara','Chapala');

    cities['United States'] = new Array();
    cities['United States']['California'] = new Array('Los Angeles','San Francisco');
    cities['United States']['Florida'] = new Array('Miami','Orlando');
    cities['United States']['New York'] = new Array('Buffalo','new York');

    function setStates() {
    cntrySel = document.getElementById('country');
    stateList = states[cntrySel.value];
    changeSelect('state', stateList, stateList);
    setCities();
    }

    function setCities() {
    cntrySel = document.getElementById('country');
    stateSel = document.getElementById('state');
    cityList = cities[cntrySel.value][stateSel.value];
    changeSelect('city', cityList, cityList);
    }

    function changeSelect(fieldID, newOptions, newValues) {
    selectField = document.getElementById(fieldID);
    selectField.options.length = 0;
    for (i=0; i<newOptions.length; i++) {
    selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
    }
    }

    // Multiple onload function created by: Simon Willison
    // http://simonwillison.net/2004/May/26/addLoadEvent/
    function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
    window.onload = func;
    } else {
    window.onload = function() {
    if (oldonload) {
    oldonload();
    }
    func();
    }
    }
    }

    addLoadEvent(function() {
    setStates();
    });

    Head

    <script type="text/javascript" src="countryStateCity.js"></script>

    Body

    <fieldset style="width: 230px;">
    <legend><strong>Make your selection</strong></legend>
    <p>
    <form name="test" method="POST" action="processingpage.php">
    <table>
    <tr>
    <td style="text-align: left;">Country:</td>
    <td style="text-align: left;">
    <select name="country" id="country" onchange="setStates();">
    <option value="Canada">Canada</option>
    <option value="Mexico">Mexico</option>
    <option value="United States">United States</option>
    </select>
    </td>
    </tr><tr>
    <td style="text-align: left;">State:</td>
    <td style="text-align: left;">
    <select name="state" id="state" onchange="setCities();">
    <option value="">Please select a Country</option>
    </select>
    </td>
    </tr><tr>
    <td style="text-align: left;">City:</td>
    <td style="text-align: left;">
    <select name="city" id="city">
    <option value="">Please select a Country</option>
    </select>
    </td>
    </tr>
    </table>
    </form>
    </fieldset>

    I have got the code to work OK but only with small content. When I load all countries, states/provinces, & cities/towns my computer runs out of memory. I need to break up the source file into maybe 1 for each country or 1 for each group of countries with the same first letter. I guess I'll need multiple lines similar to this;
    <script type="text/javascript" src="countryStateCity.js"></script>

    Maybe like this;
    <script type="text/javascript" src="country/Canada.js"></script>
    <script type="text/javascript" src="country/Mexico.js"></script>
    <script type="text/javascript" src="country/United States.js"></script>

    Can somebody provide me with amended coding?

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,241
    Please use forum BBCode tags when posting scripting.

    If your computer is running out of memory, that will be down to the issue of a memory leak, in simple terms, you wrote a script that is eating up all the available memory. You need to check and see what routine is doing that.

    Code:
    var cities = new Array();
    
    cities['Canada'] = new Array();
    cities['Canada']['Alberta'] = new Array('Edmonton','Calgary');
    cities['Canada']['British Columbia'] = new Array('Victoria','Vancouver');
    cities['Canada']['Ontario'] = new Array('Toronto','Hamilton');
    
    cities['Mexico'] = new Array();
    cities['Mexico']['Baja California'] = new Array('Tijauna','Mexicali');
    cities['Mexico']['Chihuahua'] = new Array('Ciudad Juárez','Chihuahua');
    cities['Mexico']['Jalisco'] = new Array('Guadalajara','Chapala');
    
    cities['United States'] = new Array();
    cities['United States']['California'] = new Array('Los Angeles','San Francisco');
    cities['United States']['Florida'] = new Array('Miami','Orlando');
    cities['United States']['New York'] = new Array('Buffalo','new York');
    could be stored as an object
    For example
    Code:
    var cities = {
        'Canada':{
            'Alberta':['Edmonton','Calgary'],
            'British Columbia': ['Victoria','Vancouver'],
            'Ontario': ['Toronto','Hamilton']
        },
        'Mexico': {
            'Baja California': [Tijauna','Mexicali'],
            'Chihuahua': ['Ciudad Juárez','Chihuahua'],
            'Jalisco': ['Guadalajara','Chapala']
        },
        'United States': {
            'California': ['Los Angeles','San Francisco'],
            'Florida': ['Miami','Orlando'],
            'New York': ['Buffalo','new York']
        }
    }
    then cities.Mexico.Chihuahua would be an array of two components and cities.Mexico.Chihuahua[0] would equal `Ciudad Juárez`

    what I don't see is a routine to clear the select..option if the city is changed.

    This is what I came up with
    HTML Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Select</title>
    <script>var cities = { // country.city[towns]
        'Canada':{
            'Alberta':['Edmonton','Calgary'],
            'British Columbia': ['Victoria','Vancouver'],
            'Ontario': ['Toronto','Hamilton']
        },
        'Mexico': {
            'Baja California': ['Tijauna','Mexicali'],
            'Chihuahua': ['Ciudad Juárez','Chihuahua'],
            'Jalisco': ['Guadalajara','Chapala']
        },
        'United States': {
            'California': ['Los Angeles','San Francisco'],
            'Florida': ['Miami','Orlando'],
            'New York': ['Buffalo','new York']
        }
    }
    
    selects = {
    	country:false,
    	city:false,
    	town:false
    }
    
    function processSelect( sel ){
    if(sel.selectedIndex>0){
    	var dfc = document.forms.country,
    			choice = sel.options[ sel.selectedIndex ].value; // get the selected element
    	switch( sel.name ){
    		case "city": 
    			var  states = cities[choice],			// the states to select
    				keys = Object.keys(states),	// the keys of the object selected
    				target = dfc.state;	// the form target
    			// check for existing entyeris and remove them
    			if( target.options.length > 1) clearStates(target);
    			populate( target, keys );
    			// keep record of current selection [country]
    			selects.country = choice;
    		break;
    		
    		case "state":
    			var country = selects.country,  // get the current selected city
    				towns = cities[selects.country][choice],	// the states to select
    				target = dfc.town;	// the form target
    			// check for existing entyeris and remove them
    			if( target.options.length > 1) clearTowns(target);
    			populate( target, towns );
    			// keep record of selection [city]
    			selects.city = choice;	
    		break;
    		
    		case "town":
    			selects.town = choice;
    			console.log("> Country : "+selects.country);
    			console.log("> City	 : "+selects.city);
    			console.log("> Town : "+selects.town);
    		break;
    		}
    	}
    }
    /*********************************************************/
    function clearStates( sel ){
    for(s=sel.options.length-1; s>=1; s-- ){ 
    	sel.options[s] = null;
    	}
    	clearTowns( document.forms.country.town);
    }
    /*********************************************************/
    function clearTowns( sel ){
    for(s=sel.options.length-1; s>=1; s-- ){ 
    	sel.options[s] = null;
    	}
    }
    /*********************************************************/
    function populate(target,data){
    	for (i=0; i<data.length; i++) {
    		target[ i+1 ] = new Option( data[i], data[i], false, false);
        }
    }
    
    </script>
    </head>
    <body>
    <form name="country" action="javascript:;">
      <select name="city" size="1" onchange="processSelect( this );">
        <option value="-1" selected="selected">Please select a city</option>
    	<option value="Canada">Canada</option>
    	<option value="Mexico">Mexico</option>
    	<option value="United States">United States</option>
      </select>
    <hr>
      <select name="state" size="1" onchange="processSelect( this );">
        <option value="-1" selected="selected">Please select a state</option>
      </select>
    <hr>
      <select name="town" size="1" onchange="processSelect( this );">
        <option value="-1" selected="selected">Please select a state</option>
      </select>
    </form>
    </script>
    </body>
    </html>
    Its a bit rough and ready but it works.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Sep 2015
    Posts
    19
    I'm grateful for your input.

    I've spent many months collating every country/territory, every state/province/region, and every city/town/district, in the world and the "countryStateCity.js" file is huge. If I list all the countries/territories and all the states/provinces/regions and the cities/towns/districts of the countries/territories starting with "A" & "B" everything works OK, but if I add the cities/towns/districts of the countries/territories starting with "C" the system fails, so I'm guessing it is because of a lack of memory.

    If I was to adapt the coding you provided, I would need to re-write the countryStateCity.js file again, and I don't want to do that because it will probably take me several months.

    I was hoping that the original coding in the html file could be changed so that for example when "Canada" was selected the system would open a file such as "country/Canada.js" and then it should work. If I create a file now such as "country/Canada.js" the system works but only for Canada and no other country. So I'm wanting the code that can select all the countries .js files.

  4. #4
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,241
    I would use a brief list of countries, then use AJAX to send that to the server and then use the return data from a database to populate the city field, then same for the city field, return a list that populates the town field...
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  5. #5
    Join Date
    Sep 2015
    Posts
    19
    OK, thanks but I'm only a novice and know nothing about AJAX and little about Javascript. I need to be hand fed. I was attracted to the original script because of its simplicity and I want to keep the project simple. There must be some way in Javascript for when a country is selected, then a particular source file is selected?

  6. #6
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,241
    You can read up about AJAX, theres pelnty of information, beware though, allot of subjects talk of AJAX in the JQuery sense and not in the JavaScript sense.

    https://www.w3schools.com/js/js_ajax_examples.asp gives a couple of examples, if you look at the text file example, you can call a text file that could be a simple CSV (comma separated variable) list, eg a file for each different city / state.
    Code:
    var Canada = {
            'Alberta':['Edmonton','Calgary'],
            'British Columbia': ['Victoria','Vancouver'],
            'Ontario': ['Toronto','Hamilton']
        }
    Code:
    var Mexico = {
            'Baja California': [Tijauna','Mexicali'],
            'Chihuahua': ['Ciudad Juárez','Chihuahua'],
            'Jalisco': ['Guadalajara','Chapala']
        }
    Code:
     var UnitedStates ={
            'California': ['Los Angeles','San Francisco'],
            'Florida': ['Miami','Orlando'],
            'New York': ['Buffalo','new York']
    }
    and the AJAX call

    Code:
    function getCity( cityName ) {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          eval( this.responseText );
        }
      };
      xhttp.open("GET", "./"+cityName+".txt", true);
      xhttp.send();
    }
    so calling getCity("UnitedStates"); would call the file called UnitedStates.txt which contains JavaScript written as an object, it would then be evaluated and it would create the variable UnitedStates as an object so UnitedStates.California would be an array or entries.

    You would need to edit xhttp.open("GET", "./"+cityName+".txt", true); so that the URL looks in the right place, note that because of restrictions with AJAX, you can't use this locally, you would have to use a web server to get around this restriction (in other words, you have to upload your page for testing).

    I would however look at a more generic way of gettign the data so that you have less code to write.

    You will find that allot of people freak out at the hint of using eval and claim it is dangerous, not true, it is only dangerous if it is abused needlessly and in this instance is is being used as a means to create an object to solve a problem and not being used in a malicious manner.

    You could use https://www.w3schools.com/js/js_json_parse.asp to parse a JSON string, pretty much the same sort of thing, you would still need to use AJAX to pull the file data to parse but your string would need to be properly formatted. See examples.

    I would say for your needs, this would be the most appropriate method of getting data from the server.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  7. #7
    Join Date
    Sep 2015
    Posts
    19
    I'm grateful for your input but I want to stick with Javascript and not get involved with any more languages. I want something like this;

    Code:
    <script type="text/javascript"></script>
    
    <fieldset style="width: 230px;">
    <legend><strong>Make your selection</strong></legend>
    <p>
    <form name="test" method="POST" action="processingpage.php">
    <table>
    <tr>
    <td style="text-align: left;">Country:</td>
    <td style="text-align: left;">
    <select name="country" id="country" onchange="setStates();">
      <option value="Canada">Canada</option> onselect=src="../countries/Canada.js";
      <option value="Mexico">Mexico</option> onselect= src="../countries/Mexico.js";
      <option value="United States">United States</option> onselect= src="../countries/United States.js";
    </select>
    </td>
    </tr><tr>
    <td style="text-align: left;">State:</td>
    <td style="text-align: left;">
    <select name="state" id="state" onchange="setCities();">
      <option value="">Please select a Country</option>
    </select>
    </td>
    </tr><tr>
    <td style="text-align: left;">City:</td>
    <td style="text-align: left;">
    <select name="city"  id="city">
      <option value="">Please select a Country</option>
    </select>
    </td>
    </tr>
    </table>
    </form>
    </fieldset>

  8. #8
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,241
    Well AJAX is JavaScript. If you look at another thread where someone is getting to grips with menus, you will see that creating a JSON (JavaScript Object Notation) file, you can parse it with JSON.parse in to a variable to use as an object and populate your chosen selects.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  9. #9
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,241
    for example, in a text file, if you put
    Code:
    {
        'Alberta':['Edmonton','Calgary'],
        'British Columbia': ['Victoria','Vancouver'],
        'Ontario': ['Toronto','Hamilton']
    }
    call it canada.txt

    then use AJAX (https://www.w3schools.com/js/js_ajax_examples.asp) to call that file [code]function loadDoc( file ) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "./"+file+".txt", true);
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    city = JSON.parse( this.responseText );
    }
    };
    xhttp.send();
    }

    [code]
    loadDoc("canada");
    city['Alberta'] would = ['Edmonton','Calgary'];
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  10. #10
    Join Date
    Sep 2015
    Posts
    19
    You said earlier ".... because of restrictions with AJAX, you can't use this locally, you would have to use a web server to get around this restriction (in other words, you have to upload your page for testing)." I am developing a website on my laptop so need to test locally.

    The coding you provided is confusing and I have no idea where to put it, that is if at all it can be tested locally.

    I want a simple piece of Javascript that for example when "Canada" is selected it refers to the "Canada.js" file and not the whole world as is what I've got now. I want something in Javascript similar to the snippet I posted in my previous post.

  11. #11
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,241
    Locally means on your own machine, it has to be over an internet connection from a web domain.

    If you want to use AJAX locally you would need to have a webserver kit on your laptop, something like XAMPP or WAMP or easyPHP or similar tool.

    The point of AJAX and a JSON string is to allow you to pull in the data you need. So when your selection is made ro United States, you can have your AJAX request request the United States.txt file, parse the response with JSON.parse in to a variable thats ready to then populate the subsequent options in your other drop down menus.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  12. #12
    Join Date
    Sep 2015
    Posts
    19
    I don't want to use AJAX, and I don't want to pull data.

    I want a simple piece of Javascript that when a country is selected, the system will refer to only that country's JS file. Just the same as it does now where the system only refers to the country's states/provinces.

  13. #13
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,241
    But you are pulling data already but by adding a JavaScript file after the page has loaded, AJAX does the same sort of thing which is more geared up to doing the job.

    The one issue that you can create with your method is blocking, that is where your page stops responding for the duration of the time it takes to load and render the scripts.

    AJAX runs in background and causes no system hangups, there is a difference and a reason for these different methods.

    When blocking happens, it can cause other problems with any other activity ongoing in your page as opposed to AJAX which allows the user to continue using the page whilst these background processes are happening.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  14. #14
    Join Date
    Sep 2015
    Posts
    19
    Maybe I should have phrased it differently. I want Javascript to find a file name, rather than find a name within a file. I have a text editor which can do that by macro and Javascript appears to be no different.

  15. #15
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,241
    Can you elaborate on that, where is the filename being generated?

    if you have a dropdown option, then you can use that as a storage feature for the filename needed.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles