Showing one select box option based on another select box option but getting values reset on page load

Hi All,

I have added all the Canadian Provinces and US State List and using jQuery I am displaying only Canadian Provinces when country Canada is Selected, and if US is selected only US states displayed and for any other country hide the Select box completely use the other state/provinces text box

But I am running into problem for example if a customer forgets to enter any other field in the billing page and hit continue, when the page reloads so that the customer can fill in the missing fields but for some reason the state and country options selected resets to US ( which is default ). Also if the customer moves away from the billing page and comes back to it, all the other fields holds their values except the country and state, they get reset to US.

Here is my code, anyway to make them not reset.

A sample of Countries Select box and States Select box

<select name="BillCountry" id="BillCountry">
<option value="">Select Country</option>
<option value="AS">American Samoa</option>
<option value="AQ">Antarctica</option>
<option value="CA">Canada</option>
<option value="UK">United Kingdon</option>
<option value="US">United States</option>
</select>

Open in new window


<select name="BillStates" id="BillStates">
<option value="">Select State</option>
<option class="us-states" value="AA">Armed Forces - Americas</option>
<option class="us-states" value="AE">Armed Forces - Europe</option>
<option class="us-states" value="AP">Armed Forces - Pacific</option>
<option class="us-states" value="AL">Alabama</option>
<option class="us-states" value="AK">Alaska</option>
<option class="us-states" value="AZ">Arizona</option>
<option class="ca-states" value="AB">Alberta</option>
<option class="ca-states" value="BC">British Columbia</option>
<option class="ca-states" value="MB">Manitoba</option>
<option class="ca-states" value="NB">New Brunswick</option>
<option class="ca-states" value="NF">Newfoundland</option>
</select

Open in new window


here is my jQuery
<script type="text/javascript">
$(document).ready(function($) {
  var backupBillStates = $("#BillStateSelect").html();
   checkbCountry();
  $("#BillCountry").on('change',checkbCountry);
    function checkbCountry() {            
        var bcountry = $("#BillCountry").val();
        var options = $(backupBillStates).filter(function() { return !$(this).attr("class") || $(this).attr("class").substr(0,2) == bcountry; });
        $("#BillStateSelect").html(options);
        if(bcountry=='CA') {
           $(".other-bstate input[type=text]").removeClass('needs');
            $(".other-bstate").hide();
            $(".bstateselect").show();    
        }else if(bcountry=='US') {
           $(".other-bstate input[type=text]").removeClass('needs');
            $(".other-bstate").hide();
            $(".bstateselect").show();    
        }else {
           $(".other-bstate input[type=text]").addClass('needs');
            $(".other-bstate").show();
            $(".bstateselect").hide();        
        }
    };
    
    $("#BillCountry").val("US").trigger("change");     
});
</script>
[code]

Thanks and appreciate it

Open in new window

LVL 2
niceoneishereAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dejaanbuCommented:
it always resets to US , because of the following code:
$("#BillCountry").val("US").trigger("change"); 

Open in new window

btw, which server side language r u using ? PHP?
how u r making all other fields hold their values in server code?
you have to specifiy "selected" property to the particular Option in BillCountry select box.
for ex,
<option value="AS" selected >American Samoa</option>

Open in new window

the above will make sure, when the page loads, American Samoa is selected.
MurfurFull Stack DeveloperCommented:
When you say "page reload" I take it that you are validating the form fields in a different page or the server-side element of the same page.

To prevent the page reload and loss of user input, create your validation in javascript to interrupt the submit process and validate the submitted data before allowing form submission to proceed.

Depending on the complexity of your requirement, you may want to look at jQuery but you can just as easily put in a quick and simple bit of js, see example below.

In the first instance, the browser itself can perform basic validation in that a particular field should not be empty. Simply add required to the INPUT tag attributes - see first name in the example below.

Next step is to add the validation function and giving it the instructions on what to validate and what to do in the event of failure.
Also, you will need to add the onsubmit="return validate()" in order to trigger the validation on form submission.

Obviously you can connect to the DOM elements in various ways but just bear in mind that you can have more than one element with the same name attribute but only one per id, hence I have used getElementById which guarantees you are talking to the right element.

There are any number of free validation scripts available out on the web which will allow you to go much further than simply ensuring that something has been entered, e.g. email address format, date range, phone number format etc. Some are simple and others are pretty mountainous in their abilities.

<!DOCTYPE html>
<html>
<body>

<script>
function validate() {
	
    var lastname = document.getElementById("lastname");
//	or
//	var lastname = document.getElementsByName("lastname");
//	or
//	var lastname = document.forms["testForm"]["lastname"];
    if (lastname.value == null || lastname.value == "") {
        lastname.style.border	= '1px solid red';
		lastname.placeholder	= "Last name is required";
		lastname.focus();

		// false halts form submission
		return false;
    }
//	and so on for other fields

	
}
</script>

<form name="testForm" method="POST" action="" onsubmit="return validate();">
	
	<label for firstname>First Name<input type="text" name="firstname" id="firstname" value="" required /></label>
	<br/>
	<label for lastname>Last Name<input type="text" name="lastname" id="lastname" value="" /></label>
	<br/>
	<label for phone>Phone<input type="text" name="phone" id="phone" value="" /></label>
	<br/>
	<input type="submit" value="Submit" />

</form>

</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.