Boardy
Boardy

Reputation: 36237

Set selected <select> option using jQuery based on value not text

I am working on some HTML/JavaScript code.

I have the following box.

<select style="height: 90px;" id="cboApplications" name="cboApplications[]" multiple>
   <option value="1">App 1</option>
   <option value="2">App 2</option>
   <option value="3">App 3</option>
</select>

I have the following JavaScript code

$("#cboApplications option[value=2]").attr("selected", "selected");

For some reason though, nothing gets selected, and no errors are shown.

Upvotes: 1

Views: 3360

Answers (3)

JGV
JGV

Reputation: 5197

You are very close. You need to enclose 2 with quotes, it will fix your issue.

$("#cboApplications option[value='2']").attr("selected", "selected");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select style="height: 90px;" id="cboApplications" name="cboApplications[]" multiple>
   <option value="1">App 1</option>
   <option value="2">App 2</option>
   <option value="3">App 3</option>
</select>

Upvotes: 3

Tariq
Tariq

Reputation: 2871

Use this: $("#cboApplications").val(2);

Upvotes: 0

Satpal
Satpal

Reputation: 133453

You should use .val() to set the value.

A string of text, a number, or an array of strings corresponding to the value of each matched element to set as selected/checked.

$("#cboApplications").val(2);

OR

$("#cboApplications option[value=2]").prop("selected", true);

Upvotes: 1

Related Questions