Reputation: 265
My jQuery selects the value attribute. How do I change my jQuery to select the data attribute "data-price"?
HTML:
<span id="priceToSwap3"">$238</span>
<select id="trapsize">
<option data-price="238">item1</option>
<option data-price="288">item2</option>
</select>
<select id="trapfabric">
<option data-price="0">item3</option>
<option data-price="20">item4</option>
</select>
jQuery:
$('#trapfabric, #trapsize').on('change', function() {
var $selected = $('#trapfabric, #trapsize').children(":selected");
sum = parseInt($('#trapsize').val()) + parseInt($('#trapfabric').val());
$('#priceToSwap3').html('$' + sum
);
});
Upvotes: 2
Views: 2947
Reputation: 4254
even you can get and set values based on the attribute
$("[data-price=238]").attr("data-price", 0);
Upvotes: 0
Reputation: 2511
attr("data-price");
or
data("price");
The latter being the preferable way.
In your code it would be:
sum = parseInt($('#trapsize option:selected').data('price')) + parseInt($('#trapfabric option:selected').data('price'));
More about data()
here.
Upvotes: 0
Reputation: 9370
Try:
$('#trapsize option:selected').data('price');
$('#trapfabric option:selected').data('price');
And your function should be;
$('#trapfabric, #trapsize').on('change', function() {
sum = parseInt($('#trapsize option:selected').data('price')) + parseInt($('#trapfabric option:selected').data('price'));
$('#priceToSwap3').html('$' + sum);
})
Upvotes: 0
Reputation: 36551
try this
$('#trapsize option:selected').data('price');
using your code
$('#trapfabric, #trapsize').on('change', function() {
sum = parseInt($('#trapsize option:selected').data('price')) + parseInt($('#trapfabric option:selected').data('price'));
$('#priceToSwap3').html('$' + sum);
});
example fiddle here
Upvotes: 1
Reputation: 388436
To fetch the data attribute $(el).data('price')
var sum = $('#trapsize option:selected').data('price') + $('#trapfabric option:selected').data('price');
Demo: Fiddle
Upvotes: 4