nsilva
nsilva

Reputation: 5614

jQuery - Check If any select option is selected

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>

Upvotes: 24

Views: 62677

Answers (6)

Adam Grey
Adam Grey

Reputation: 31

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
}

Upvotes: 0

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

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
}

Upvotes: 1

K D
K D

Reputation: 5989

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
  }
});

});

Upvotes: 4

Richard Dalton
Richard Dalton

Reputation: 35793

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/

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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
}

Upvotes: 37

bipen
bipen

Reputation: 36531

try this

$('#sel-destination-tour').val() == ""){
    //nothing selected;
}else{
    //something selected;
}

Upvotes: 4

Related Questions