[javascript] Check if option is selected with jQuery, if not select a default

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 :)

This question is related to javascript jquery forms dom html-select

The answer is


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

if (!$("#select").find("option:selected").length){
  //
}

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


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


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

$("option[value*='2']").attr('selected', 'selected');
// 2 for example, add * for every option

<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length)
   $("#mySelect").val( 3 );

});
</script>

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

$("#mySelect").val( 3 );

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.


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

$(".Result").html($("option:selected").text());

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

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.


$("#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


No need to use jQuery for this:

var foo = document.getElementById('yourSelect');
if (foo)
{
   if (foo.selectedIndex != null)
   {
       foo.selectedIndex = 0;
   } 
}

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


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

Unobtrusive JavaScript


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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to html-select

How can I get new selection in "select" in Angular 2? How to show disable HTML select option in by default? Remove Select arrow on IE Bootstrap 3 select input form inline Change <select>'s option and trigger events with JavaScript How to use a Bootstrap 3 glyphicon in an html select Creating a select box with a search option Drop Down Menu/Text Field in one How to have a default option in Angular.js select box How to set the 'selected option' of a select dropdown list with jquery