Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
IvanConway

State/Country Form Fields

Recommended Posts

Being reasonably new at generating javascript, I am trying to create a form where the client enters the State of Birth (Queensland, Victoria, Tasmania etc) and by using javascript the Country of Birth is auto filled with "Australia".
I have got to a stage where I can auto fill the Country field with a small js script with either onClick or mouseOver however I am at a loss with the code to be able to fill the Country field by entering the state name in the State field.  At 75 I'm running out of brains and would appreciate a little help please.

Autofill.html

Share this post


Link to post
Share on other sites

The trouble with input of state you are relying on the user to enter the name correctly, thats why dropdowns are used.

        <form>
            <p><label>State of Birth: </label>
                <select id="state" name="state" onchange="autoFill(this)">
                    <option value="Queensland">Queensland</option>
                    <option value="Tasmania">Tasmania</option>
                    <option value="Florida">Florida</option>
                    <option value="Victoria">Victoria</option>

                </select>
            <p>
                <label>Country of Birth: </label>
                <input type="text" id="country" name="country">
            </p>
        </form>
        <script type="text/javascript">

            var stateArray = [[0, 'Queensland'], [0, 'Victoria'], [0, 'Tasmania'], [1, 'Florida']];

            var countryArray = ['Australia', 'America']; //0 from above is index to Australia, 1 to USA
            //Arrays always start from 0

            function autoFill(elem) {
                var countryIndex = "";
                for (i = 0; i < stateArray.length; i++) {
                    if (elem.value === stateArray[i][1])//if value from dropdown matches looped thro state array 2nd state values
                    {   //store index value to country
                        countryIndex = stateArray[i][0];
                        document.getElementById('country').value = countryArray[countryIndex]; 
                        // use index value to get country array value and show in input
                        break; //stop loop
                    }

                }
            }
        </script>

 

  • Thanks 1

Share this post


Link to post
Share on other sites

Unless you are going to use the value of state from dropdown somewhere else, you can simply change the value from dropdown to the actual country that the text state of options is showing. You then wouldn't require any arrays just the retrieved value from selected state.

  • Like 1

Share this post


Link to post
Share on other sites
On 3/20/2018 at 6:58 PM, dsonesuk said:

Unless you are going to use the value of state from dropdown somewhere else, you can simply change the value from dropdown to the actual country that the text state of options is showing. You then wouldn't require any arrays just the retrieved value from selected state.

Thank you for your help, I am learning a lot.  Is it possible however to avoid using the drop down options by just having the user input their State in the State field and the Country field auto fills with Australia. I have attached my html tester file of what I have done so far. 

I have inserted all of the states in the state array to which I will have to also add the short forms as well: ie, QLD for Queensland and NSW for New South Wales etc in the event that the clients inserts the short form of the state.

Tester.html

Share this post


Link to post
Share on other sites

You can put an event listener on the state field to check for things that might match a country and auto-select the matching option if you want to do that.  You'll need to have an array or something or states and countries so you can match them up.

Share this post


Link to post
Share on other sites

Change select element to input type text, change onchange to onkeyup. To make it easier whatever the user enters uppercase or lowercase, the if condition comparison will always be lowercase to match array lowercase value with both using .toLowerCase() function.

 

Share this post


Link to post
Share on other sites

My thanks to dsonesuk, with his help I have achieved my goal with the following:

<script>
           var stateArray = [[0, 'Qld'], [0, 'NSW'], [0, 'Vic'], [0, 'Tas'], [0, 'ACT'], [0, 'SA'], [0, 'WA'], [0, 'NT'], [0, 'Queensland'], [0, 'New South Wales'], [0, 'Victoria'], [0, 'Tasmania'], [0, 'Australian Capital Territory'], [0, 'South Australia'], [0, 'Western AUstralia'], [0, 'Northern Territory']];

            var countryArray = ['Australia']; 
             function autoFill(elem) {
                var countryIndex = "";
                for (i = 0; i < stateArray.length; i++) {
                    if (elem.value === stateArray[1]) {

                       countryIndex = stateArray[0];
                        document.getElementById('country').value = countryArray[countryIndex]; 
                         break; 
                    }

                }
            }
        </script>

<form>
            <p><label>State of Birth: </label>
                    <input type="text" id="state" name="state" onkeyup="autoFill(this)">
                    
            <p>
                <label>Country of Birth: </label>
                <input type="text" id="country" name="country">
            </p>
        </form>

Edited by IvanConway

Share this post


Link to post
Share on other sites

Actually it won't work because your referencing the correct item in array

	 if (elem.value === stateArray[1]) {
	                       countryIndex = stateArray[0];
	

Should be

 if (elem.value === stateArray[i][1]) { 
	                       countryIndex = stateArray[i][0]; 

Forget above, apparently if you paste as text and save, it removes

[i]

part, maybe thinks as adding italics code me thinks. YEP! thats it! see it changes to italics from the first point I mentioned.

Always use '<>' (adding code) in menu above OR

[ code ][ /code ] (without spaces)

if not available in mobile

 

 

Edited by dsonesuk

Share this post


Link to post
Share on other sites

Thanks to your help and advice, the attached tester .html works how I want.  However, have I gone overboard with the JS code?  Am I able to tidy it up a bit.

Tester.html

Share this post


Link to post
Share on other sites

IF you are duplicating JavaScript, you are doing it wrong! You need and identifier that will distinguish groom input from bride input and the obvious one is the first letter 'g' and 'b'. By striping out 'state' you are left with identifier for which partner you are currently targeting, then by adding this identifier variable to 'state' and 'country' you are now targeting that specific partners inputs.

function autoFill(elem) {

                var coupleIdentifier = elem.id.replace("state", "");
                var countryInput = document.getElementById(coupleIdentifier + 'country');
                var stateInput = document.getElementById(coupleIdentifier + 'state');
                countryInput.value = "";
                var countryIndex = "";

                for (i = 0; i < stateArray.length; i++) {
                    countryInput.value = "";
                    if (stateArray[i][1].toLowerCase().indexOf(elem.value.toLowerCase()) === 0 && elem.value !== "") {

                        if (elem.value.length > 2 && elem.value.length === stateArray[i][1].length) {
                            countryIndex = stateArray[i][0];
                            stateInput.value = stateArray[i][1].substring(0, elem.value.length);
                            countryInput.value = countryArray[countryIndex];

                            break;
                        }
                        else if (elem.value.length > 2 && elem.value.length !== stateArray[i][1].length)
                        {

                            stateInput.value = stateArray[i][1].substring(0, elem.value.length);
                        }
                        else {
                            stateInput.value = elem.value;

                        }
                    }
                }
            }

 

Share this post


Link to post
Share on other sites

I have tried unsuccessfully to apply your suggested code to my attached js file.  To be honest, I don't have enough understanding as yet  to know how to apply it. I understand the identifier concept and thought I had it covered in my js file by identifying the stateArrays and the Element Id's.  The file is working and unfortunately at this stage of my learning, I am unsure of how to improve it.

autofill.js

Share this post


Link to post
Share on other sites
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0">
        <title>Document Title</title>
        <script>
            var stateArray = [[0, 'Qld'], [0, 'NSW'], [0, 'Vic'], [0, 'Tas'], [0, 'ACT'], [0, 'SA'], [0, 'WA'], [0, 'NT'], [0, 'Queensland'], [0, 'New South Wales'], [0, 'Victoria'], [0, 'Tasmania'], [0, 'Australian Capital Territory'], [0, 'South Australia'], [0, 'Western Australia'], [0, 'Northern Territory']];
            var countryArray = ['Australia'];
            function autoFill(elem) {

                var coupleIdentifier = elem.id.replace("state", "");
                var countryInput = document.getElementById(coupleIdentifier + 'country');
                var stateInput = document.getElementById(coupleIdentifier + 'state');
                countryInput.value = "";
                var countryIndex = "";

                for (i = 0; i < stateArray.length; i++) {
                    countryInput.value = "";
                    if (stateArray[i][1].toLowerCase().indexOf(elem.value.toLowerCase()) === 0 && elem.value !== "") {

                        if (elem.value.length > 2 && elem.value.length === stateArray[i][1].length) {
                            countryIndex = stateArray[i][0];
                            stateInput.value = stateArray[i][1].substring(0, elem.value.length);
                            countryInput.value = countryArray[countryIndex];

                            break;
                        }
                        else if (elem.value.length > 2 && elem.value.length !== stateArray[i][1].length)
                        {

                            stateInput.value = stateArray[i][1].substring(0, elem.value.length);
                        }
                        else {
                            stateInput.value = elem.value;

                        }
                    }
                }
            }
        </script>
        <style>
            #my_form label, #my_form input {min-width: 200px; display: inline-block; max-width: 290px;}
        </style>
    </head>
    <body>
        <form id="my_form">
            <p>
                <label>Groom State of Birth: </label>
                <input type="text" id="gstate" name="gstate" onkeyup="autoFill(this)"/>
            <p>
                <label>Groom Country of Birth: </label>
                <input type="text" id="gcountry" name="gcountry"/>
            <p> **********************************************
            <p>
                <label>Bride State of Birth: </label>
                <input type="text" id="bstate" name="bstate" onkeyup="autoFill(this)"/>
            <p>
                <label>Bride Country of Birth: </label>
                <input type="text" id="bcountry" name="bcountry"/>
            </p>
        </form>
    </body>
</html>

 

Share this post


Link to post
Share on other sites

OR maybe

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0" />
        <title>Document Title</title>
        <style type="text/css">
            .selectclass {
                border: 1px solid #ccc;
                width: 200px;
            }
            ul.selectclass {
                background-color: #fff;
                border-color: currentcolor #ccc #ccc;
                border-image: none;
                border-style: none solid solid;
                border-width: medium 1px 1px;
                list-style-type: none;
                margin: 0;
                padding: 0;
                position: absolute;
                width: 290px;
                z-index: 100;
                box-shadow: 2px 4px 9px -4px;
                display: none;
                top:100%;
                left:2em;
            }
            ul.selectclass li {border-top: 1px solid #ccc; padding: 2px; cursor:pointer; }
            ul.selectclass li:hover {background-color: #4df}
            .datalist_wrap {display: inline-block; position: relative;}
            .datalist_wrap > * {display: block;}

            .partner_wrap > label {
                vertical-align: top;
            }
            #couple_location label {
                display: inline-block;
                width: 170px;
            }
            ul.selectclass li span:last-child {float: right;}
        </style>
    </head>
    <body>
        <form>
            <div id="couple_location">
                <div class="partner_wrap">
                    <label>Groom State of Birth: </label>
                    <div class="datalist_wrap">
                        <input class="selectclass" type="text" id="gstate" name="gstate" onkeyup="autoFill(this)"/>
                        <ul id="gdatalist" class="selectclass">

                        </ul>
                    </div>
                </div>
                <p>
                    <label>Groom Country of Birth: </label>
                    <input class="selectclass" type="text" id="gcountry" name="gcountry"/>
                </p>
                <p> **********************************************</p>
                <div class="partner_wrap">
                    <label>Bride State of Birth: </label>
                    <div class="datalist_wrap">
                        <input class="selectclass" type="text" id="bstate" name="bstate" onkeyup="autoFill(this)"/>
                        <ul id="bdatalist" class="selectclass">

                        </ul>
                    </div>
                </div>
                <p>
                    <label>Bride Country of Birth: </label>
                    <input class="selectclass" type="text" id="bcountry" name="bcountry"/>
                </p>

            </div>
        </form>

        <script type="text/javascript">

            var stateArray = [[0, 'Qld'], [0, 'NSW'], [0, 'Vic'], [0, 'Tas'], [0, 'ACT'], [0, 'SA'], [0, 'WA'], [0, 'NT'], [0, 'Queensland'], [0, 'New South Wales'], [0, 'Victoria'], [0, 'Tasmania'], [0, 'Australian Capital Territory'], [0, 'South Australia'], [0, 'Western Australia'], [0, 'Northern Territory'], [1, 'Queensland']];
            var countryArray = [['Australia', 'AUS'], ['America', 'USA']];
            var coupleIdentifier = "";
            var stateDatalist;
            function autoFill(elem) {

                coupleIdentifier = elem.id.replace("state", "");
                var countryInput = document.getElementById(coupleIdentifier + 'country');
                var stateInput = document.getElementById(coupleIdentifier + 'state');
                stateDatalist = document.getElementById(coupleIdentifier + 'datalist');
                stateDatalist.style.display = "none";
                stateDatalist.innerHTML = "";

                countryInput.value = "";

                totalfoundcount = 0;
                exactmatchcount = 0;

                for (i = 0; i < stateArray.length; i++) {
                    if (stateArray[i][1].toLowerCase().indexOf(elem.value.toLowerCase()) === 0 && elem.value !== "") {
                        totalfoundcount++;
                    }

                    if (stateArray[i][1].toLowerCase().indexOf(elem.value.toLowerCase()) === 0 && elem.value.length === stateArray[i][1].length) {
                        exactmatchcount++;
                    }
                }

                if (totalfoundcount > 0 && exactmatchcount !== 1) {

                    for (i = 0; i < stateArray.length; i++) {
                        if (stateArray[i][1].toLowerCase().indexOf(elem.value.toLowerCase()) === 0) {

                            stateDatalist.style.display = "inline-block";
                            var selectListItem = document.createElement("LI");
                            /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
                            //first span containing state name
                            var selectListItemSpan = document.createElement("span");
                            selectListItemText = document.createTextNode(stateArray[i][1]);
                            selectListItemSpan.appendChild(selectListItemText);
                            selectListItem.appendChild(selectListItemSpan);
                            /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
                            //second span identifying abbreviated country location, helps
                            //if duplicate state name are found from diffrent countrys
                            var selectListItemSpan = document.createElement("span");
                            selectListItemText = document.createTextNode('(' + countryArray[stateArray[i][0]][1] + ')');
                            selectListItemSpan.appendChild(selectListItemText);
                            selectListItem.appendChild(selectListItemSpan);
                            /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/

                            selectListItem.setAttribute("onclick", "insertHintSuggestion(this,'" + coupleIdentifier + "', this.childNodes[1].innerHTML)");
                            stateDatalist.appendChild(selectListItem);
                        }
                    }

                }
                if (exactmatchcount > 0 && exactmatchcount < 2) {
                    for (i = 0; i < stateArray.length; i++) {
                        if (stateArray[i][1].toLowerCase().indexOf(elem.value.toLowerCase()) === 0 && elem.value.length === stateArray[i][1].length) {
                            countryInput.value = countryArray[stateArray[i][0]][0];
                            stateInput.value = stateArray[i][1];
                            break;
                        }

                    }

                }
            }

            function insertHintSuggestion(elem, identifier, AbbrCountryName) {
                var cleanAbbrCountryName = AbbrCountryName.replace(/[()]/g, '');
                var state = document.getElementById(identifier + 'state');
                var country = document.getElementById(identifier + 'country');
                for (i = 0; i < stateArray.length; i++) {

                    if (stateArray[i][1] === elem.childNodes[0].innerHTML && countryArray[stateArray[i][0]][1] === cleanAbbrCountryName) {
                        country.value = countryArray[stateArray[i][0]][0];
                        state.value = stateArray[i][1];
                    }
                }
                stateDatalist.style.display = "none";
            }


        </script>
    </body>
</html>

 

Share this post


Link to post
Share on other sites

My sincerest Thank You for your advice and assistance with this project.  I understand why you are quoted as a Guru.  I also realize that I have a long way to go with javascript.

Share this post


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

×