212

Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.

(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
meleyal
  • 32,252
  • 24
  • 73
  • 79

18 Answers18

274

While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.

<select id="mySelect" multiple="multiple">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length) {
    $("#mySelect option[value='3']").attr('selected', 'selected');
  }
});
</script>
Rishi Kulshreshtha
  • 1,748
  • 1
  • 24
  • 35
Joe Lencioni
  • 10,231
  • 18
  • 55
  • 66
  • 87
    The selection would be easier to read like this: `$("#mySelect").val(3);` – Jørn Schou-Rode Dec 09 '09 at 12:07
  • 6
    This got me on the right track, but I needed to do this: `$("#mySelect option")[2]['selected'] = true;` Figured that out after investigating the object structures in Firebug. – semperos Aug 12 '10 at 21:08
  • 28
    As of jQuery 1.6 you can set the property directly. `$("#mySelect").prop("selectedIndex", 2)` – gradbot May 16 '11 at 01:31
  • 1
    The .val(x) version does not work in Internet Explorer 8, so @gradbot has it right, as this works in all Browsers. – Sorcy Jul 18 '12 at 11:15
30

No need to use jQuery for this:

var foo = document.getElementById('yourSelect');
if (foo)
{
   if (foo.selectedIndex != null)
   {
       foo.selectedIndex = 0;
   } 
}
FlySwat
  • 172,459
  • 74
  • 246
  • 311
15

This question is old and has a lot of views, so I'll just throw some stuff out there that will help some people I'm sure.

To check if a select element has any selected items:

if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }

or to check if a select has nothing selected:

if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }

or if you're in a loop of some sort and want to check if the current element is selected:

$('#mySelect option').each(function() {
    if ($(this).is(':selected')) { .. }
});

to check if an element is not selected while in a loop:

$('#mySelect option').each(function() {
    if ($(this).not(':selected')) { .. }
});

These are some of the ways to do this. jQuery has many different ways of accomplishing the same thing, so you usually just choose which one appears to be the most efficient.

Gavin
  • 7,544
  • 4
  • 52
  • 72
  • "not" has not worked for me $('#mySelect option').each(function() { if ($(this).not(':selected')) { .. } }); So used a negation on is like if (!$(this).is(':selected')) { .. } Browser: Chrome; Jquery version: 3.1.1 – Anil kumar Nov 10 '17 at 10:10
12

lencioni's answer is what I'd recommend. You can change the selector for the option ('#mySelect option:last') to select the option with a specific value using "#mySelect option[value='yourDefaultValue']". More on selectors.

If you're working extensively with select lists on the client check out this plugin: http://www.texotela.co.uk/code/jquery/select/. Take a look the source if you want to see some more examples of working with select lists.

Community
  • 1
  • 1
9

Here is my function changing the selected option. It works for jQuery 1.3.2

function selectOption(select_id, option_val) {
    $('#'+select_id+' option:selected').removeAttr('selected');
    $('#'+select_id+' option[value='+option_val+']').attr('selected','selected');   
}
sata
  • 91
  • 1
  • 1
7
<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length)
   $("#mySelect").val( 3 );

});
</script>
Rup
  • 33,765
  • 9
  • 83
  • 112
Ram Prasad
  • 71
  • 1
  • 1
3

I already came across the texotela plugin mentioned, which let me solve it like this:

$(document).ready(function(){
    if ( $("#context").selectedValues() == false) {
    $("#context").selectOptions("71");
    }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
meleyal
  • 32,252
  • 24
  • 73
  • 79
3

Easy! The default should be the first option. Done! That would lead you to unobtrusive JavaScript, because JavaScript isn't needed :)

Unobtrusive JavaScript

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Martin Labuschin
  • 516
  • 4
  • 16
2

Look at the selectedIndex of the select element. BTW, that's a plain ol' DOM thing, not JQuery-specific.

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
2

This was a quick script I found that worked... .Result is assigned to a label.

$(".Result").html($("option:selected").text());
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
Joel
  • 41
  • 1
1
if (!$("#select").find("option:selected").length){
  //
}
Sliq
  • 15,937
  • 27
  • 110
  • 143
Avinash Saini
  • 1,203
  • 11
  • 10
1

You guys are doing way too much for selecting. Just select by value:

$("#mySelect").val( 3 );
giagejoe
  • 39
  • 1
1

I found a good way to check, if option is selected and select a default when it isn't.

    if(!$('#some_select option[selected="selected"]').val()) {
        //here code if it HAS NOT selected value
        //for exaple adding the first value as "placeholder"
        $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');
    }

If #some_select has't default selected option then .val() is undefined

0

Change event on the select box to fire and once it does then just pull the id attribute of the selected option :-

$("#type").change(function(){
  var id = $(this).find("option:selected").attr("id");

  switch (id){
    case "trade_buy_max":
      // do something here
      break;
  }
});
0

I was just looking for something similar and found this:

$('.mySelect:not(:has(option[selected])) option[value="2"]').attr('selected', true);

This finds all select menus in the class that don't already have an option selected, and selects the default option ("2" in this case).

I tried using :selected instead of [selected], but that didn't work because something is always selected, even if nothing has the attribute

0

If you need to explicitly check each option to see if any have the "selected" attribute you can do this. Otherwise using option:selected you'll get the value for the first default option.

var viewport_selected = false;      
$('#viewport option').each(function() {
    if ($(this).attr("selected") == "selected") {
        viewport_selected = true;
    }
});
zeman
  • 29
  • 3
0
$("option[value*='2']").attr('selected', 'selected');
// 2 for example, add * for every option
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
0
$("#select_box_id").children()[1].selected

This is another way of checking an option is selected or not in jquery. This will return Boolean (True or False).

[1] is index of select box option

Andriy M
  • 76,112
  • 17
  • 94
  • 154
Taimoor Changaiz
  • 10,250
  • 4
  • 49
  • 53