Elijah Yang
Elijah Yang

Reputation: 265

How to use data attribute with jQuery?

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

Answers (7)

Krishnamoorthy Acharya
Krishnamoorthy Acharya

Reputation: 4254

even you can get and set values based on the attribute

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

Upvotes: 0

wassup
wassup

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

Anujith
Anujith

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

bipen
bipen

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

abhijit
abhijit

Reputation: 1968

You can use jquery attr

$("your dom").attr("data-price")

Upvotes: 0

Arun P Johny
Arun P Johny

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

Merec
Merec

Reputation: 2761

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

Upvotes: 0

Related Questions