Skip to content Skip to sidebar Skip to footer

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 $sel

Solution 1:

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.

DEMO

Solution 2:

You are binding event to two elements #trapsize, #trapfabric if you want to get the source element you need to use $(this);

jsfiddle

$('#trapfabric, #trapsize').on('change', function() {    
    $('#priceToSwap3').text( '$' + $(':selected', this).data("price") );
});

Solution 3:

We had a similar scenario wherein we assign security value(1,2,3 as security level) for each input. We have to change the security values "0" when the user logs into the system.

Eg:

<inputtype="text"security="3"id="super-admin" /><inputtype="text"security="2"id="main-admin" /><inputtype="text"security="1"id="normal-user" /><script>functionuserValidation(userType){

if(userType="super-admin"){
   $("[security=1]").attr("security", 0);
   $("[security=2]").attr("security", 0);
   $("[security=3]").attr("security", 0);
 }
if(userType="main-admin"){
  $("[security=1]").attr("security", 0);
  $("[security=2]").attr("security", 0);
 }
 if(userType="normal-user"){
   $("[security=1]").attr("security", 0);
 }
}
<script>

Post a Comment for "How To Select The Html5 Data Attribute In Jquery?"