javascript - How to get custom attribute value in jquery or JS from radio buttons? - Stack Overflow

I got a piece of HTML:<input type="radio" name="radioBtn" onChange="rdbtn()

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.

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.

Share Improve this question edited Feb 1, 2015 at 22:09 Deduplicator 45.8k7 gold badges72 silver badges123 bronze badges asked May 21, 2014 at 12:11 TheKolanNTheKolanN 713 silver badges13 bronze badges 3
  • 2 if you want to use .data() the attribute has to be data-isprm="true" – Jeff Shaver Commented May 21, 2014 at 12:12
  • @TheKolanN: Which jquery version you are using? – Ishan Jain Commented May 21, 2014 at 12:24
  • @JeffShaver: I use jQuery 2.1.1 – TheKolanN Commented May 21, 2014 at 12:30
Add a ment  | 

2 Answers 2

Reset to default 6

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');

You need to prefix data- with custom attributes to work with .data(). Also you have to use name when using attribute value selector since you have not specified id of radio option and use name which you have specified i.e. radioBtn

Use

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

Then

$('input[name=radioBtn]').data("isprm");

DEMO

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745143070a4613518.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信