tags:

views:

27

answers:

2

Typical noob question. :-) I looked at some of similar questions raised here, the solutions are too complicated for me to make them work. Or they don't really work? Anyway what this code does is it hides/shows the Province input when the option selected is USA/notUSA. The default selection is the option with value United states. To make it distinct from other options, I assigned a class=us to it and class=notus to others.

  function showhideProvinceInput(){
     if($("#countries option[class='notus']")){
      $('#provincelabel').fadeIn("slow");
      $('#provinceinput').fadeIn("slow");
     }
     if($("#countries option[class='us']")) {
      $('#provincelabel').fadeOut(0);
      $('#provinceinput').fadeOut(0);
     }
    }

    $(document).ready(function(){ 
        $('#countries').change(function() {
            showhideProvinceInput();
       });
   });

It partially works, at least in "show" case. Partially because the input shows and then hides in 1 or so seconds. I have not tried hiding it because showing it doesn't fully work yet. :-) Any help?

+2  A: 

I think you are missing a part of your selector - you want to check if the selected option has the class of notus:

function showhideProvinceInput(){
     if($("#countries option:selected").hasClass("notUs")){
      $('#provincelabel').fadeIn("slow");
      $('#provinceinput').fadeIn("slow");
     }
     else {
      $('#provincelabel').fadeOut(0);
      $('#provinceinput').fadeOut(0);
     }
    }
Paddy
Damn, too quick for me :D... I've slapped this in jsfiddle.net, have a look (@joann) http://jsfiddle.net/q9bwR/
ILMV
Works perfectly! didn't know hasClass function. Thanks!
Joann
@ILMV - JSFiddle - nice looking site. Thanks for the pointer.
Paddy
A: 

Your function should look something like this if you're using classes:

function showhideProvinceInput(){
 if($("#countries option.notus:selected").length){
  $('#provincelabel, #provinceinput').fadeIn("slow");
 }
 else {
  $('#provincelabel, #provinceinput').hide();
 }
}

$(function(){ 
  $('#countries').change(showhideProvinceInput);
});

The main changes here are you can use a .class selector, and use :selected to only look for the selected <option>, then use .length to see if that selector found any items. Also you can combine the later selectors and use .hide() for the instant .fadeOut(0).

Also there's no need for the anonymous function if this handler is all you're calling :)

Nick Craver
Neat. Thanks! I am going for this.
Joann