Set selected option of select box

JqueryHtmlJquery SelectorsHtml Select

Jquery Problem Overview


I want to set a option that was selected previously to be displayed on page load. I tried it with the following code:

$("#gate").val('Gateway 2');

with

<select id="gate">
	<option value='null'>- choose -</option>
	<option value='gateway_1'>Gateway 1</option>
	<option value='gateway_2'>Gateway 2</option>
</select>

But this does not work. Any ideas?

Jquery Solutions


Solution 1 - Jquery

This definitely should work. Here's a demo. Make sure you have placed your code into a $(document).ready:

$(function() {
    $("#gate").val('gateway_2');
});

Solution 2 - Jquery

$(document).ready(function() {
    $("#gate option[value='Gateway 2']").prop('selected', true);
    // you need to specify id of combo to set right combo, if more than one combo
});

Solution 3 - Jquery

$('#gate').val('Gateway 2').prop('selected', true);

Solution 4 - Jquery

  $("#form-field").val("5").trigger("change");

Solution 5 - Jquery

I have found using the jQuery .val() method to have a significant drawback.

<select id="gate"></select>
$("#gate").val("Gateway 2");

If this select box (or any other input object) is in a form and there is a reset button used in the form, when the reset button is clicked the set value will get cleared and not reset to the beginning value as you would expect.

This seems to work the best for me.

For Select boxes

<select id="gate"></select>
$("#gate option[value='Gateway 2']").attr("selected", true);

For text inputs

<input type="text" id="gate" />
$("#gate").attr("value", "your desired value")

For textarea inputs

<textarea id="gate"></textarea>
$("#gate").html("your desired value")

For checkbox boxes

<input type="checkbox" id="gate" />
$("#gate option[value='Gateway 2']").attr("checked", true);

For radio buttons

<input type="radio" id="gate" value="this"/> or <input type="radio" id="gate" value="that"/>
$("#gate[value='this']").attr("checked", true);

Solution 6 - Jquery

That works fine. See this fiddle: http://jsfiddle.net/kveAL/

It is possible that you need to declare your jQuery in a $(document).ready() handler?

Also, might you have two elements that have the same ID?

Solution 7 - Jquery

This would be another option:

$('.id_100 option[value=val2]').prop('selected', true);

Solution 8 - Jquery

I had the same problem.

Solution: add a refresh.

$("#gate").val('Gateway 2');
$("#gate").selectmenu('refresh');

Solution 9 - Jquery

Some cases may be

$('#gate option[value='+data.Gateway2+']').attr('selected', true);

Solution 10 - Jquery

I know there are several iterations of answers but now this doesn't require jquery or any other external library and can be accomplished pretty easy just with the following.

document.querySelector("#gate option[value='Gateway 2']").setAttribute('selected',true);

<select id="gate">
    <option value='null'>- choose -</option>
    <option value='Gateway 1'>Gateway 1</option>
    <option value='Gateway 2'>Gateway 2</option>
</select>

Solution 11 - Jquery

I know this has an accepted answer, but in reading the replies on the answer, I see some things that I can clear up that might help other people having issues with events not triggering after a value change.

This will select the value in the drop-down:

$("#gate").val("gateway_2")

If this select element is using JQueryUI or other JQuery wrapper, use the refresh method of the wrapper to update the UI to show that the value has been selected. The below example is for JQueryUI, but you will have to look at the documentation for the wrapper you are using to determine the correct method for the refresh:

$("#gate").selectmenu("refresh");

If there is an event that needs to be triggered such as a change event, you will have to trigger that manually as changing the value does not fire the event. The event you need to fire depends on how the event was created:

If the event was created with JQuery i.e. $("#gate").on("change",function(){}) then trigger the event using the below method:

$("#gate").change();

If the event was created using a standard JavaScript event i.e.

Solution 12 - Jquery

My problem

get_courses(); //// To load the course list
$("#course").val(course); //// Setting default value of the list

I had the same issue . The Only difference from your code is that I was loading the select box through an ajax call and soon as the ajax call was executed I had set the default value of the select box

The Solution

get_courses();
   setTimeout(function() {
     $("#course").val(course);
  }, 10);

Solution 13 - Jquery

I had a problem where the value was not set because of a syntax error before the call.

$("#someId").value(33); //script bailed here without showing any errors Note: .value instead of .val
$("#gate").val('Gateway 2'); //this line didn't work.

Check for syntax errors before the call.

Solution 14 - Jquery

$(function() {
$("#demo").val('hello');
});

Solution 15 - Jquery

// Make option have a "selected" attribute using jQuery

var yourValue = "Gateway 2";

$("#gate").find('option').each(function( i, opt ) {
    if( opt.value === yourValue ) 
        $(opt).attr('selected', 'selected');
});

Solution 16 - Jquery

Addition to @icksde and @Korah (thx both!)

When building the options with AJAX the document.ready may be triggered before the list is built, so

This doesn't work

$(document).ready(function() {
	$("#gate").val('Gateway 2');
});

This does

A timeout does work but as @icksde says it's fragile (I did actually need 20ms in stead of 10ms). It's better to fit it inside the AJAX function like this:

$("#someObject").change(function() {
	$.get("website/page.php", {parameters}, function(data) {
		$("#gate").append("<option value='Gateway 2'">" + "Gateway 2" + "</option>");
		$("#gate").val('Gateway 2');
	}, "json");
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUpCatView Question on Stackoverflow
Solution 1 - JqueryDarin DimitrovView Answer on Stackoverflow
Solution 2 - JqueryZkohView Answer on Stackoverflow
Solution 3 - JqueryMarty HirschView Answer on Stackoverflow
Solution 4 - JqueryMohd BashirView Answer on Stackoverflow
Solution 5 - JqueryMikeView Answer on Stackoverflow
Solution 6 - JqueryJames WisemanView Answer on Stackoverflow
Solution 7 - JqueryKent AguilarView Answer on Stackoverflow
Solution 8 - JqueryPostedView Answer on Stackoverflow
Solution 9 - JqueryHemilView Answer on Stackoverflow
Solution 10 - JquerySyWillView Answer on Stackoverflow
Solution 11 - JqueryStephenView Answer on Stackoverflow
Solution 12 - JqueryKorahView Answer on Stackoverflow
Solution 13 - JqueryhowardView Answer on Stackoverflow
Solution 14 - JqueryGaurav RaiView Answer on Stackoverflow
Solution 15 - JqueryRonnel Castillo OcampoView Answer on Stackoverflow
Solution 16 - JqueryCor KoomenView Answer on Stackoverflow