Jump to content

State/Country Form Fields


IvanConway

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

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

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

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

 

Link to comment
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
Link to comment
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
Link to comment
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;

                        }
                    }
                }
            }

 

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

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

 

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

 

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...