Sam
Sam

Reputation: 3

How to select the label of an <option> given its value, and given a name for the <select>

Given the following code:

<select name='starttime' onChange='cells(this);'><option value='1'>2004Q1</option><option value='2'>2004Q2</option></select>
<select name='endtime' onChange='cells(this);'><option value='48'>2015Q4</option><option value='47'>2015Q3</option></select>

How can I access the text of say, the option with value = 1 of the "starttime" <select> (i.e. 2004Q1)? I can access the value of this element by using the following jQuery code:

$('[name=starttime]').val()

However, I'd like to instead specify a value and name, and get the associated text.

Upvotes: 0

Views: 75

Answers (1)

Badacadabra
Badacadabra

Reputation: 8497

Is this what you need?

console.log($('[name="starttime"] [value="1"]').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="starttime">
  <option value="1">2004Q1</option>
  <option value="2">2004Q2</option>
</select>

<select name="endtime">
  <option value="48">2015Q4</option>
  <option value="47">2015Q3</option>
</select>

Upvotes: 1

Related Questions