最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论