Reputation: 69
I want to ask how can i sum data-price from images onclick with jquery?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<body>
<img id="1" src="" data-price="5">
<img id ="2" src="" data-price="10">
<div id="sum"></div>
</body>
</html>
thanks in advance.
Upvotes: 0
Views: 3925
Reputation: 35963
You can get data-price using .data()
Try this:
$('#1, #2').click(function() {
alert( $(this).data('price') );
var sum = parseInt( $('#1').data('price')) + parseInt( $('#2').data('price'));
alert(sum);
$('#sum').html(sum);
});
Upvotes: 1
Reputation: 318182
Target the ID of the images, and attach an event handler, then on click, get the data attribute with data()
$('#1, #2').on('click', function() {
alert( $(this).data('price') );
});
If you somehow need to sum this up in the #sum element, you should ask specifically about that.
EDIT:
and now you did ?
$('#1, #2').on('click', function() {
var data1 = parseInt( $('#1').data('price') ,10);
var data2 = parseInt( $('#2').data('price') ,10);
$('#sum').text(data1 + data2);
});
Upvotes: 0