396

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?

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601
  • 10
    Actually that is how it should work, are you sure you set the value in document.ready() ? Maybe the code is executed when the selectbox isn't ready yet. – Morph Jan 13 '11 at 12:39

17 Answers17

566

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

$(function() {
    $("#gate").val('gateway_2');
});
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 5
    ok, when I drop down the list it is highlighted but not displayed as first element in the list – DarkLeafyGreen Jan 13 '11 at 12:41
  • 1
    @ArtWorkAD, what do you mean by first element in the list? I don't quite understand your requirement. – Darin Dimitrov Jan 13 '11 at 12:42
  • 2
    ahh I declared it not in the document ready function...thanks! – DarkLeafyGreen Jan 13 '11 at 12:43
  • 7
    Not as good as setting the attribute "selected" to "selected". – Adal May 16 '13 at 19:48
  • 6
    @Adal Why is this not as good as setting the 'selected' attribute to 'selected'? – Shawn May 30 '13 at 19:33
  • 1
    Hey Shawn, depending on your situation, setting the selected attribute can be a more explicit way of doing things. However I've come across cases where some java-script was triggered on value change and not "selected" attribute so I guess you should take my comment with a grain of salt. – Adal May 31 '13 at 20:24
  • 27
    Just in case anyone else wonders, the `'Gateway 2'` passed to the function `val` matches the value of the `value` attribute of the select option, not its text. See [this JSFiddle](http://jsfiddle.net/kenny_evitt/CpXVB/1178/), which is a very mildly edited version of Darin's demo, for an example of what I mean. – Kenny Evitt Aug 19 '14 at 17:51
  • Sometimes its common to want to select the first item (for initialisation routine). In which case you can avoid having to hardcode a value, and just use $("#gate").val($("#gate option:first").val()); – carpii Jan 16 '17 at 00:43
  • I have a problem selecting a value in select2. can you help me over this? – always-a-learner Jun 18 '17 at 12:27
  • 1
    @Adal I came across the event not being fired, too. So, for example if you need to trigger an `onChange` event, just append `.change()`. – Erutan409 Jul 26 '17 at 16:19
  • Using jQuery Mobile don't forget to update the UI so your selection displays. $('#select').selectmenu().selectmenu('refresh'); – Olmstov Feb 01 '18 at 17:55
192
$(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
});
andrewtweber
  • 24,520
  • 22
  • 88
  • 110
Zkoh
  • 2,932
  • 3
  • 18
  • 14
42

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

Appulus
  • 18,630
  • 11
  • 38
  • 46
Marty Hirsch
  • 661
  • 6
  • 7
  • 2
    Very similar to `$('#your-select-box-id :nth-child(2)').prop('selected', true)` which works, with visual update of the drop-box. – Big Rich Jan 23 '18 at 13:44
  • 1
    Only one that worked for me. Suspect because I am using a custom select library. – Louis M. Nov 13 '18 at 10:29
25
  $("#form-field").val("5").trigger("change");
Mohd Bashir
  • 949
  • 1
  • 8
  • 17
  • 3
    It would have been nice if you included some info around this. This is a great example of how you SHOULD do this, IF you have code that is watching for changes to the select. – sean.boyer Jul 31 '17 at 16:32
  • 1
    Thank you very much this is exactly what i was looking for. This is the perfect answer if you are updating the values of select box with ajax. – Akash Desai Dec 05 '20 at 16:02
  • Needed to add `.trigger("change");` for mine to work. Thanks. – Luke Galea Oct 29 '21 at 14:10
18

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);
Mike
  • 265
  • 2
  • 10
7

This would be another option:

$('.id_100 option[value=val2]').prop('selected', true);
Kent Aguilar
  • 5,048
  • 1
  • 33
  • 20
6

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?

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
5

I had the same problem.

Solution: add a refresh.

$("#gate").val('Gateway 2');
$("#gate").selectmenu('refresh');
Unheilig
  • 16,196
  • 193
  • 68
  • 98
Posted
  • 59
  • 1
  • 1
4

Some cases may be

$('#gate option[value='+data.Gateway2+']').attr('selected', true);
dbc
  • 104,963
  • 20
  • 228
  • 340
Hemil
  • 227
  • 3
  • 16
3

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>
SyWill
  • 61
  • 3
2

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. then trigger the event using the below method:

var JSElem = $("#gate")[0];
if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    JSElem.dispatchEvent(evt);
} else {
    JSElem.fireEvent("onchange");
}
Stephen
  • 58
  • 6
1

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);
Korah
  • 11
  • 1
  • 1
    you analyzed the problem correct, but the solution is bad and fragile. you have to use a callback function attached to your ajax call – icksde Jan 04 '16 at 10:18
0

$(document).ready(function() {
  $('#selectBoxId option[value="val2"]').prop('selected', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectBoxId">
  <option value="val1">Option1</option>
  <option value="val2">Option2</option>
  <option value="val3">Option3</option>
</select>
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer). – Ethan Jun 25 '22 at 02:37
-1

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.

howard
  • 29
  • 4
-1
$(function() {
$("#demo").val('hello');
});
Howli
  • 12,291
  • 19
  • 47
  • 72
Gaurav Rai
  • 17
  • 4
-2
// 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');
});
-2

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 may give some insight.

A timeout does work but as @icksde says it's fragile. 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");
});