Testing123
Testing123

Reputation: 70

To get the object of the selected option of dropdown using values

I have a dropdown and I need to get the entire object using the value. I can get it using the text with contains but the same does not work by value. Here is my code. What am I doing wrong?

//var option = $("#car option:contains('Volvo')");
//alert(option.attr('value'));

var option = $("#car option:contains('value1')");
alert(option.attr('value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="car">
  <option value="value1">Volvo</option>
  <option value="value2">Saab</option>
  <option value="value3">Mercedes</option>
  <option value="value4">Audi</option>
</select>

The commented portion works fine. I need to find a way to get the entire object using the value instead.

Upvotes: 0

Views: 166

Answers (4)

dave
dave

Reputation: 575

var e = document.getElementById("car");
var selectedOption = e.options[e.selectedIndex].value;
alert(selectedOption);

First you target the selection list element with variable e, then you use the state of that element and assign it to selectedOption.

Upvotes: 0

danny barlev
danny barlev

Reputation: 224

The issue is that jQuery :contains refer only to the text node of the element,not the content of an attribute.

you can use selector of an attribute in the following way:

var option = $("#car option[value=value1]");
alert(option.attr('value'));

Upvotes: 1

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

While :contains selector select elements that contain the specified text. You can use [attribute = "value"] .. I highly recommended to read about Selectors Here

//var option = $("#car option:contains('Volvo')");
//alert(option.attr('value'));

var option = $("#car option[value='value1']");
alert(option.attr('value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="car">
  <option value="value1">Volvo</option>
  <option value="value2">Saab</option>
  <option value="value3">Mercedes</option>
  <option value="value4">Audi</option>
</select>

Upvotes: 1

The_Outsider
The_Outsider

Reputation: 1925

//var option = $("#car option:contains('Volvo')");
//alert(option.attr('value'));

var option = $("#car option[value=value1]");
alert(option.attr('value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="car">
  <option value="value1">Volvo</option>
  <option value="value2">Saab</option>
  <option value="value3">Mercedes</option>
  <option value="value4">Audi</option>
</select>

Upvotes: 1

Related Questions