开发者

How do i get attribute values from html inputs?

I have a radio button that looks like this:

<input class="MCQRadio" id="MCQ" mcq-id="1" name="MCQ" question-id="1" type="radio" value="MCQ" /> MCQ

[EDIT]

When i cli开发者_如何学运维ck the radiobutton, and several radio buttons have the same class name, how do i retrive the question-id value and mcq-id value from the specific button? Preferably with jQuery.

I have already set up a click handler like this:

$(document).ready(function () {

    $('.MCQRadio').click(function () {


$('#MCQ').attr('question-id')
$('#MCQ').attr('mcq-id')


var mcq-id = $('#MCQ').attr("mcq-id");
var question-id = $('#MCQ').attr("question-id");


Most of the answers given already are correct. I would make one addition to avoid traversing the DOM twice to find your radio button element.

//Store the jQuery object in a variable so that it's only retrieved once
var $myRadio = $('#MCQ');

//Get your attributes
var mcq-id = $myRadio.attr("mcq-id");
var question-id = $myRadio.attr("question-id");

You could also attach to the click event of all the radio buttons (by class selector) and grab the attributes in the event handler:

$('.MCQRadio').click(function() {
    //Use $(this) to grab the attribute value of the selected element
    var mcq-id = $(this).attr('question-id');
    var question-id = $(this).attr('mcq-id');
});


The other answers already show you how to get the particular attributes. But since you added in your edit that you want to get the attributes from the particular one that was clicked you can try:

$('.MCQRadio').click(function() {

   $(this).attr('question-id');
   $(this).attr('mcq-id');

});


These will return the values you want.

$('#MCQ').attr('mcq-id')
$('#MCQ').attr('question-id')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜