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
    );
});
3
  • 2
    Or, even better, .data('price') Commented Mar 1, 2013 at 12:10
  • 1
    possible duplicate of How to select the HTML5 data attribute in jQuery? Commented Mar 1, 2013 at 12:13
  • @roXon yes it's a duplicate because I didn't phrase my question properly in the last post and hence it was confusing. Commented Mar 1, 2013 at 12:16

7 Answers 7

4

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

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

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

hi Arun, i have tried your suggestion also with parseInt but in my case it doesn't work: jsfiddle.net/wesweatyoushop/3H3dA/31
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

Comments

0

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

Comments

0

You can use jquery attr

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

Comments

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);
})  

Comments

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.

Comments

0

even you can get and set values based on the attribute

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.