2

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
    );
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Elijah Yang
  • 265
  • 1
  • 7
  • 16

7 Answers7

4

To fetch the data attribute $(el).data('price')

var sum = $('#trapsize option:selected').data('price') + $('#trapfabric option:selected').data('price');

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • hi Arun, i have tried your suggestion also with parseInt but in my case it doesn't work: http://jsfiddle.net/wesweatyoushop/3H3dA/31/ – alex Oct 27 '14 at 17:20
1

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

bipen
  • 36,319
  • 9
  • 49
  • 62
0

$('option').attr('data-price');

Merec
  • 2,751
  • 1
  • 14
  • 21
0
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.

wassup
  • 2,333
  • 2
  • 21
  • 30
0

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);
})  
Anujith
  • 9,370
  • 6
  • 33
  • 48
0

You can use jquery attr

$("your dom").attr("data-price")
abhijit
  • 1,958
  • 3
  • 28
  • 39
0

even you can get and set values based on the attribute

$("[data-price=238]").attr("data-price", 0);