I am trying to use jQuery to get the html5 data-sku="002" from an element with a class of selected.
Ideally would like to set a variable if the data-sku="002" and has a class of selected. Then I could use if/else or show()/hide() to enable or disable other elements on my page later on.
<li data-sku="002" data-id="1590" data-price="120"
data-label="You have selected: Premium" class="selected">
<span class="price"><sup>€</sup>120</span>
<span class="title-plan">Premium
<span><p>Premium Package</p>
</span>
</span>
<a href="#" class="btn btn-submit-price-plan select-plan">Select</a>
<div class="clearfix"></div>
</li>
I have made a example on jsfiddle http://jsfiddle.net/gkrrbnyy/2/ But I am shooting in the dark a bit.
Any ideas on the best way to approach this? As I am not very experienced with jquery.
If I understand correctly you want:
jQuery('.selected').data('sku')
for example:
jQuery(".select-plan").click(function(){
alert('Selectecd sku is: '+jQuery('.selected').data('sku'));
});
JSFiddle: http://jsfiddle.net/cbhsnqeg/1/ (updated)
And here why: https://api.jquery.com/data/
You could also use jQuery(".select-plan").attr('data-sku')
.
Try substituting jQuery(".selected[data-sku=002]").text()
for jQuery(".selected").find('[data-sku=002]').text()
; .selected
has data-*
attribute , not .selected
child nodes , which .find()
traverses
You can use this
$(".select-plan").click(function() {
// gives the element that has class=selected and data-sku='002'
temp = $(".selected[data-sku=002]")
//$(temp).data('sku') gives the value of the element's attribute
//data-sku
$("#myID").html($(temp).data('sku'));
});
Selector .selected[data-sku=002]
can be used for finding the element which has both.
jQuery(".select-plan").click(function(){
mfvariable = jQuery(".selected[data-sku=002]").length;
if( mfvariable > 0 )
alert('Exists');
else
alert('Not found');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.