3

I want to select an option on a html select. For example, a select with:

 <select id="list">
   <option>Jan</option>
   <option>Feb</option>
   <option>Mar</option>
   <option>Apr</option>
 </select>

I can do something like this if I know the value for the option, for example:

 <option value="0">Jan</option>

 $("#list option:eq(0)").attr("selected", "selected");

Can I use the value between the option tag?

4
  • option should have value attribute, then simply set select value. And FYI, using recent jQuery version, prop() to set selected property is the preferred method Commented Feb 3, 2014 at 20:24
  • I was trying to avoid repeating the value twice. Commented Feb 3, 2014 at 20:25
  • If you just have to use the text, you could always do $('#list option:contains(Mar)').prop('selected', true) Commented Feb 3, 2014 at 20:28
  • You confuse value and text Commented Feb 3, 2014 at 20:29

2 Answers 2

4

Use .val(value), Here in example I have use Mar to set as value

Set the value of each element in the set of matched elements.

$("#list").val('Mar')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="list">
    <option>Jan</option>
    <option>Feb</option>
    <option>Mar</option>
    <option>Apr</option>
</select>

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

Comments

1

Add value

<select id="list">
  <option value="jan">Jan</option>
  <option value="feb">Feb</option>
  <option value="mar">Mar</option>
  <option value="apr">Apr</option>

Then use jquery

$('#list').val( 'jan' );

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.