1

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.

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but for some reason this hasn't worked. Still doesn't get selected and no errors
Thanks this has worked after all, as I mentioned in another answer, I was calling the functions in the wrong order to populate and select
@Boardy, I would still recommend you to use either .val() or .prop() Go through stackoverflow.com/questions/5874652/prop-vs-attr Now Its up to you to decide whether to use best practice or not
I found when I used the val it would only set 1 item and I need to be select multiple items
1

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

3 Comments

Thanks but neither of these have worked for me for some reason
@Boardy, See it works jsfiddle.net/satpalsingh/bygp5kve Can you share more information? Are you using AJAX or some other framework?
D'oh, I was calling a couple of functions in the wrong order, I was selecting it, then populating it. Thanks for your help
0

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

1 Comment

Providing some explanation in your answer will help your readers to learn.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.