Solved

Using jQuery show/ hide options of one select box based on the value selected of another select box

Posted on 2014-03-27
16
12,794 Views
Last Modified: 2014-03-31
I have 4 select boxes one is called BillCountries, ShipCountries and  BillStates, ShipStates

I am running small javascript based on jQuery that if the country selected is CA and then in the States Select Box just display all the options of Canadian Provinces, other wise for any other country just display the default US States

The problem is the script works fine in FireFox but any other browser like Chrome or IE it does not work at all, when I select the country as CA it just does not display the Canadian Provinces. Instead just displays Select State

here is sample of BillCountries & ShipCountries 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>

<select name="ShipCountry" id="ShipCountry">
<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

now for the States
<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>

<select name="ShipStates" id="ShipStates">
<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 the script I am using
<script type="text/javascript">
 $(document).ready(function() {  
   $("#BillCountry").change(function () {
     if($("#BillCountry").val()=='CA'){
	    $(".us-states").css("display", "none");
		$(".ca-states").css("display", "block");
		} else {
		 $(".us-states").css("display", "block");
		$(".ca-states").css("display", "none");	 
   }
   });
   
      $("#ShipCountry").change(function () {
     if($("#ShipCountry").val()=='CA'){
	    $(".us-states").css("display", "none");
		$(".ca-states").css("display", "block");
		} else {
		 $(".us-states").css("display", "block");
		$(".ca-states").css("display", "none");	 
   }
   });
   
});
</script>

Open in new window


Thanks a lot
0
Comment
Question by:niceoneishere
  • 7
  • 7
  • 2
16 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 39959376
You cannot 'hide' an option tag in a dropdown (except in FF).
I suggest you separate your options into hidden divs and then when a country is selected you replace the content of the state dropdown with the relevant state options.

Example here
http://jsfiddle.net/GaryC123/pM5fn/1/
0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 200 total points
ID: 39959560
Test page : http://jsfiddle.net/77y8q/

jQuery(function($) {
    var backupShipStates = $("#ShipStates").html();
    $("#ShipCountry").change(function() {
        var country = $(this).val().toLowerCase();
        var options = $(backupShipStates).filter(function() { return !$(this).attr("class") || $(this).attr("class").substr(0,2) == country; });
        $("#ShipStates").html(options);
    });
});

Open in new window

0
 
LVL 1

Author Comment

by:niceoneishere
ID: 39959751
Thanks for replying, Gary one quick question is it necessary to add the class to countries because I have over 200 countries

and Savant its not working in Chrome and IE

Thanks again
0
 
LVL 58

Expert Comment

by:Gary
ID: 39959835
Leakim's solution won't work in IE8 and lower because filter wasn't added til IE9

For my solution, you need someway to tie the option to the div and a class the easiest way.
Another way could be to select by index - so the first country will target the first div, the second country the second div and so on.
0
 
LVL 1

Author Comment

by:niceoneishere
ID: 39959846
Thanks Gary appreciate it, so where would I be adding select by index sir
0
 
LVL 58

Expert Comment

by:Gary
ID: 39959868
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39959968
0
 
LVL 58

Expert Comment

by:Gary
ID: 39960072
@ niceoneishere

Leakim's solution above should work fine as well.
Ignore my comment about the filter - its wrong as far as jQuery is concerned
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 1

Author Comment

by:niceoneishere
ID: 39960121
Thanks Gary and Leakim and yes I started new and Leakim solution works but I have couple of questions,

First in Leakim Solution if any country other than US or CA is selected hid the State Select box completely and display a input type text box so the customer can enter the state

Thanks again and appreciate it
0
 
LVL 1

Author Comment

by:niceoneishere
ID: 39960443
Hi Guys I am looking to extend this solution so if you guys want me to close and open one more question I can. Please let me know

THanks
0
 
LVL 58

Expert Comment

by:Gary
ID: 39960454
Which solution are you using?
0
 
LVL 1

Author Comment

by:niceoneishere
ID: 39960471
Thanks for replying Gary, Sir I went with Leakim solution as I was able to integrate with my custom shopping cart code. here is the final code I ended up with

<script type="text/javascript">
$(document).ready(function($) {
    var backupBillStates = $("#BillStates").html();
    $("#BillCountry").change(function() {
        var bcountry = $(this).val().toLowerCase();
        var options = $(backupBillStates).filter(function() { return !$(this).attr("class") || $(this).attr("class").substr(0,2) == bcountry; });
        $("#BillStates").html(options);
    });
   
    var backupShipStates = $("#ShipStates").html();
    $("#ShipCountry").change(function() {
        var scountry = $(this).val().toLowerCase();
        var options = $(backupShipStates).filter(function() { return !$(this).attr("class") || $(this).attr("class").substr(0,2) == scountry; });
        $("#ShipStates").html(options);
    });
	
	
});
</script>

Open in new window


Here is what I am trying to achieve

1) Default states should always be US States as my default country is US but for some reason when the page is displayed the first time its showing both US and Canadian Provinces

2) I have a input text box like below

			<div class="other-states">
				<label class="italic" for="ShipState">Other State/Province:</label>
				<input type="text" name="ShipStates" id="OtherShipStates" value="" class="textfield">
			</div>

Open in new window


Is there anyway this input only shows for any country other than US and CA, at the same time hide BillStates and ShipStates for other countries except US and CA.

I know I can extend the above script but I am getting confused where I would add the if clause

Thanks and appreciate it
0
 
LVL 58

Accepted Solution

by:
Gary earned 300 total points
ID: 39960490
<script>
$(document).ready(function($) {
    var backupBillStates = $("#BillStates").html();
    $("#BillCountry").change(function() {
        var bcountry = $(this).val().toLowerCase();
        var options = $(backupBillStates).filter(function() { return !$(this).attr("class") || $(this).attr("class").substr(0,2) == bcountry; });
        $("#BillStates").html(options);
    });
   
    var backupShipStates = $("#ShipStates").html();
    $("#ShipCountry").change(function() {
        var scountry = $(this).val().toLowerCase();
        var options = $(backupShipStates).filter(function() { return !$(this).attr("class") || $(this).attr("class").substr(0,2) == scountry; });
        $("#ShipStates").html(options);
    });
	
	$("#BillCountry").val("US").trigger("change")
});
</script> 

Open in new window

0
 
LVL 1

Author Comment

by:niceoneishere
ID: 39960603
Thanks appreciate it, I extend it more to hide and show the billstates and input text box like below but the if clause is not firing properly sir, whats happening is if the countries are US and CA, the input text div is being hidden as it set to hide by default but
if I select any other country nothing happens.

<script type="text/javascript">
$(document).ready(function($) {
    var backupBillStates = $("#BillStates").html();
    $("#BillCountry").change(function() {
        var bcountry = $(this).val().toLowerCase();
        var options = $(backupBillStates).filter(function() { return !$(this).attr("class") || $(this).attr("class").substr(0,2) == bcountry; });
        $("#BillStates").html(options);
    });
   
    var backupShipStates = $("#ShipStates").html();
    $("#ShipCountry").change(function() {
        var scountry = $(this).val().toLowerCase();
        var options = $(backupShipStates).filter(function() { return !$(this).attr("class") || $(this).attr("class").substr(0,2) == scountry; });
        $("#ShipStates").html(options);
    });
	
	$("#BillCountry").val("US").trigger("change")
	
	if($("#BillCountry").val()=='US' || $("#BillCountry").val()=='CA') {
	      $("#bill-states").css("display", "block");
		  $("#OtherBillState").css("display", "none");
	}else if($("#BillCountry").val()!=='US' || $("#BillCountry").val()!=='CA') {
	      $("#bill-states").css("display", "none");
		  $("#OtherBillState").css("display", "block");        
	}
	
    if($("#ShipCountry").val()=='US' || $("#ShipCountry").val()=='CA') {
	      $("#ship-states").css("display", "block");
		  $("#OtherShipState").css("display", "none");
	}else if($("#ShipCountry").val()!=='US' || $("#ShipCountry").val()!=='CA') {
	      $("#ship-states").css("display", "none");
		  $("#OtherShipState").css("display", "block");        
	}
});
</script>

Open in new window


I  have wrapped the BillStates and ShipStates select box inside a div's like below

<div id="bill-states">
<select id="BillStates"> </select>
</div>
<div id="OtherBillStates">
<input type="text" value="" />
</div>

<div id="ship-states">
<select id="ShipStates"> </select>
</div>
<div id="OtherShipStates">
<input type="text" value="" />
</div>

Open in new window

0
 
LVL 58

Expert Comment

by:Gary
ID: 39960614
...
var bcountry = $(this).val().toLowerCase();
if(bcountry=="us" || bcountry=="ca"){
     $("#OtherShipStates input").hide()
}
else{
     $("#OtherShipStates input").show()
}
...

Open in new window

0
 
LVL 1

Author Closing Comment

by:niceoneishere
ID: 39967241
Thanks Guys :)
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

This article describes how to create custom column layout styles for Bootstrap. The article uses 5 columns to illustrate the concept, but the principle can be extended to any number of columns.
Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now