Reputation: 152
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
Reputation: 253308
Assuming you want the attribute from the selected <option>
:
$('#bu').click(function() {
alert($('.p1add1 option:selected').attr('item_name'));
});
If you want to get all the attributes:
$('#bu').click(function() {
alert($('.p1add1 option').map(function(){
return this.getAttribute('item_name');
}).get().join(', '));
});
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'));
});
References:
Upvotes: 0
Reputation: 22480
$('#bu').click(function() {
alert($('.p1add1').children('option:selected').attr('item_name'));
});
Upvotes: 1