24

Basically I have a select option which pulls all the 'Tour Names' from a database as $touroptions. $touroptions can contain anything from 1-20 values (select options).

What I need to do is have a jQuery function to do as follows so:-

If (any option) #sel-destination-tour is selected {
//DO SOMETHING
}
ELSE {
//DO SOMETHING ELSE
}

I'm just not sure how I could do this.

HTML

<select name="sel-destination-tour" id="sel-destination-tour" class="input-select-tour">

    <option value="0"></option>

    <?php echo $touroptions ?>

</select>
user229044
  • 232,980
  • 40
  • 330
  • 338
nsilva
  • 5,184
  • 16
  • 66
  • 108

6 Answers6

37

You can check whether a option by testing the value attribute of the select

if($('#sel-destination-tour').val()){
    // do something
} else {
    // do something else
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 6
    what if the option's value is 0? – Rob Apr 10 '15 at 21:01
  • It's better to check against `null`, since `0` might be a valid option value, but it would evaluate to `false` in your case. I.e. `$('#sel-destination-tour').val() != null`. – user2340939 Sep 21 '21 at 18:48
4

try this

$('#sel-destination-tour').val() == ""){
    //nothing selected;
}else{
    //something selected;
}
bipen
  • 36,319
  • 9
  • 49
  • 62
4

track the change event of select and do your stuffs accordingly

$(function(){

 $("#sel-destination-tour").change(function(){

 if($(this).val() !="0")
  {
    // logic goes here
  }
  else
  {
   // no option is selected
  }
});

});
K D
  • 5,889
  • 1
  • 23
  • 35
1

Assuming that you have the first item as shown in your example, this will do it...

if ($("#sel-destination-tour").val() != "0") {
    // nothing selected
} else {
    // something selected
}
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
0

Check the val() (assuming 0 is no value):

if ($('#sel-destination-tour').val() != 0) {
   // has a value selected
} 
else {
   // does not have a value selected
}

Example - http://jsfiddle.net/infernalbadger/RrtT7/

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
  • Just a comment : `.val()` method wont work in some cases, i dont know the correct situations, it happens in FF ( especially with large set of options that `change` is triggerd programically ) – Red Mar 27 '13 at 12:24
0

In my situation val() was returning [] and coming up as true. So I changed it to:

if($('#sel-destination-tour').val()[0]){
    // do something
} else {
    // do something else
}
Adam Grey
  • 31
  • 4