user3407278
user3407278

Reputation: 1273

How can I find get attribute of a select tag where value = something using jquery?

How can I get the price attribute's value where #products.option value = 6.

<select id="products">
<option value="2" price="60.00">Product 1</option>
<option value="4" price="40.00">Product 2</option>
<option value="6" price="40.00">Product 2</option>
<option value="8" price="40.00">Product 2</option>
</select>

Upvotes: 1

Views: 102

Answers (4)

Gnanadurai Asudoss
Gnanadurai Asudoss

Reputation: 279

You can get it with

var price = $('#products option[value="6"]').attr('price');

Upvotes: 0

Tushar
Tushar

Reputation: 87203

You can select the element by it's attribute and value.

alert($('#products option[value="6"]').attr('price'));

Demo: http://jsfiddle.net/tusharj/rhf0q9nt/

Docs: https://api.jquery.com/attribute-equals-selector/

EDIT

Thanks to @satpal:

Use data-* prefixed custom attributes to store arbitary data on element.

HTML

<select id="products">
    <option value="2" data-price="60.00">Product 1</option>
    <option value="4" data-price="40.00">Product 2</option>
    <option value="6" data-price="40.00">Product 2</option>
    <option value="8" data-price="40.00">Product 2</option>
</select>

Javascript

$('#products option[value="6"]').data('price');

Demo: http://jsfiddle.net/tusharj/7c7aet9w/

Upvotes: 2

kapantzak
kapantzak

Reputation: 11750

Use the attr() function:

var price = $('#products option[value=6]').attr('price');

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

You can

1) use attribute equals selector for getting option with value equal to 6:

2) use .attr('price') to get the value for above option

var price = $('option[value=6]').attr('price');

Working Demo

Upvotes: 1

Related Questions