Aptivus
Aptivus

Reputation: 433

jquery get data attribute of input field on change

I am trying to get the data attribute of this radio box:

<div id="corrieriContainer">
    <label><input checked="checked" type="radio" name="spedizione" data-courier="DHL" value="8.56">&euro; 8.56</label>
    <label><input type="radio" name="spedizione" data-courier="FEDEX" value="6.23">&euro; 6.23</label>
</div>

with this code, but it doesn't work:

$("#corrieriContainer").on('change','input[type=radio][name=spedizione]',function(){
var valore = $(this).prop('checked',true).val();
var corriere = $(this).prop('checked',true).data('courier');
    alert(corriere);
});

I always get "undefined" value. Why? I can correctly get $(this).prop('checked',true).val();, but not the data-attribute.

Can you help me understand?

Thank you

Upvotes: 0

Views: 1510

Answers (1)

Eddie
Eddie

Reputation: 26844

You dont really need .prop('checked',true), this is used to assign a value to a radio button or checkbox programmatically.

Since users are clicking it manually to change the value, no need for it.

$(function() {
  $("#corrieriContainer").on('change', 'input[type=radio][name=spedizione]', function() {
    var valore = $(this).val();
    var corriere = $(this).data('courier');

    alert(corriere);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="corrieriContainer">
  <label><input checked="checked" type="radio" name="spedizione" data-courier="DHL" value="8.56">&euro; 8.56</label>
  <label><input type="radio" name="spedizione" data-courier="FEDEX" value="6.23">&euro; 6.23</label>
</div>

Upvotes: 2

Related Questions