Search code examples
javascriptjqueryhtmlcustom-attributes

How to get custom attribute value in jquery or JS from radio buttons?


I got a piece of HTML:

<input type="radio" name="radioBtn" onChange="rdbtn()" value="100" isprm="true">
<input type="radio" name="radioBtn" onChange="rdbtn()" value="110" isprm="true">

and I want to pass the custom attribute value into a variable. Here is what I tried and does not work:

function rdbtn(){
   var radioVal = $(this).val();
   var radioPRM = $("input[id=radioVal]:checked").attr('isprm');
   ...
}

and

$('input[id=radioVal]').data("isprm");

No luck. Do you have any ideas how to make it work? Thanks.


Solution

  • Firstly, isprm is not a valid attribute so your HTML is invalid. If you need to store ancillary data with an element use a data-* attribute:

    <input type="radio" name="radioBtn" onChange="rdbtn()" value="100" data-isprm="true">
    <input type="radio" name="radioBtn" onChange="rdbtn()" value="110" data-isprm="true">
    

    You can then use data() to retrieve the value:

    var radioPRM = $('input[name="radioBtn"]:checked').data('isprm');