abaft
abaft

Reputation: 152

How can I get selected list attributes in JQuery

I wan't this alert box to show the attribute item_name when the button is clicked. I have JQuery.

Here is the code i'm trying to use it dosn't work though

HTML

<select class="p1add1">
    <option class="op1" value="3.74" item_name='BOWL'>Bowl   - £3.74</option>
    <option class="op2" value="7.53" item_name='COSTER'>Coster - £7.53 (six pack)</option>
    <option class="op3" value="5" item_name='CLOCK'>Clock  - £5.00</option>
</select>
<input type='button' value="Go!" id='bu' />

JQuery

$('#bu').click(function() {
    alert($('.p1add1').attr('item_name'));
});

JSfiddle - http://jsfiddle.net/LYv2W/

Upvotes: 0

Views: 67

Answers (3)

David Thomas
David Thomas

Reputation: 253308

Assuming you want the attribute from the selected <option>:

$('#bu').click(function() {
    alert($('.p1add1 option:selected').attr('item_name'));
});

JS Fiddle demo.

If you want to get all the attributes:

$('#bu').click(function() {
    alert($('.p1add1 option').map(function(){
        return this.getAttribute('item_name');
    }).get().join(', '));
});

JS Fiddle demo.

Though if you want to use custom attributes, and would like your document to validate (assuming you're using html 5), I'd strongly advise using data-* attributes instead:

<select class="p1add1">
    <option class="op1" value="3.74" data-item_name='BOWL'>Bowl   - £3.74</option>
    <option class="op2" value="7.53" data-item_name='COSTER'>Coster - £7.53 (six pack)</option>
    <option class="op3" value="5" data-item_name='CLOCK'>Clock  - £5.00</option>
</select>
<input type='button' value="Go!" id='bu' />

With the jQuery:

$('#bu').click(function() {
    alert($('.p1add1 option:selected').data('item_name'));
});

JS Fiddle demo.

References:

Upvotes: 0

Thomas Junk
Thomas Junk

Reputation: 5676

Simply:

alert($('.p1add1 :selected').attr("item_name"));

Fiddle

Upvotes: 0

caramba
caramba

Reputation: 22480

$('#bu').click(function() {
    alert($('.p1add1').children('option:selected').attr('item_name'));
});

http://jsfiddle.net/LYv2W/1/

Upvotes: 1

Related Questions