Elijah Yang Elijah Yang - 4 years ago 187
Javascript Question

How to select the HTML5 data attribute in jQuery?

My current jQuery selects the value attribute. How do I change my jQuery to select the data attribute "data-price"?

$('#trapfabric, #trapsize').on('change', function() {
var $selected = $('#trapfabric, #trapsize').children(":selected");
sum = parseInt($('#trapsize').val()) + parseInt($('#trapfabric').val());
$('#priceToSwap3').html('$' + sum

I know I have to fit something like this in the above but I can't get it to work:




<span id="priceToSwap3"">$238</span>

<select id="trapsize" onChange="swapImage()">
<option data-price="238">foo</option>
<option data-price="288">foo</option>

<select id="trapfabric" onChange="swapImage()">
<option data-price="0">foo</option>
<option data-price="20">foo</option>

Answer Source

I believe this is what you want:

var $elements = $('#trapfabric, #trapsize');
$elements.on('change', function() {
     var $selected = $elements.children(":selected");
     var sum = 0;

     $selected.each(function() {
         sum += $(this).data('price');

     $('#priceToSwap3').html('$' + sum);

You have to iterate over the selected elements to get the price datum of each of them.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download