0

I want to set the 'selected' attribute in a select option list with javascript/jquery. I have the select element in a jquery object, I just want to add the "selected" attribute to and item in the list.

$(mySelect).html() looks like this;

<option value="LININGER LAKE">LININGER LAKE</option>
<option value="MOOREDALE LAKE">MOOREDALE LAKE</option>
<option value="CARTER LAKE">CARTER LAKE</option>

I need to find the "CARTER LAKE" option and add the selected attribute to it so the HTML looks like this

<option value="LININGER LAKE">LININGER LAKE</option>
<option value="MOOREDALE LAKE">MOOREDALE LAKE</option>
<option value="CARTER LAKE" selected="selected">CARTER LAKE</option>

I know this can't be that hard, I'm just having a brain fart!

4
  • 1
    Why not just set the selectedIndex or value of the containing <select> element? Commented Sep 19, 2014 at 15:34
  • Can you post a complete code example please? What's mySelect? Commented Sep 19, 2014 at 15:35
  • Have you tried $(yourSelectSelector).val('CARTER LAKE')? Commented Sep 19, 2014 at 15:36
  • I was framing this problem wrong, I should not have been digging into the html, just sticking to jquery methods was much easier. Per Yury Tarabanko answer, setting the .val() on the select element did the trick. Thanks for all the fast replies and help! Commented Sep 19, 2014 at 16:39

5 Answers 5

2

As simple as $(mySelect).val('CARTER LAKE')

Demo

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

1 Comment

Duh... I was making this WAY too complicated!! Thanks for bringing back to earth!
2

Use the jQuery Attribute Equals selector:

$(mySelect).find('option[value="CARTER LAKE"]').prop("selected", "selected");

Comments

2
$('option[value="CARTER LAKE"]').prop( "selected" );

or

$('option[value="CARTER LAKE"]').attr( "selected", "selected" );

Comments

2

Try .contains() as shown

 $("select option:contains('CARTER LAKE')").attr('selected','selected')

OR

 $("select option:contains('CARTER LAKE')").prop('selected',true)

DEMO

Comments

1

Try by attr()

$(document).ready(function(){
  
$('option[value="CARTER LAKE"]').attr( "selected", "selected" );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="LININGER LAKE">LININGER LAKE</option>
<option value="MOOREDALE LAKE">MOOREDALE LAKE</option>
<option value="CARTER LAKE">CARTER LAKE</option>
  </select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.