Domanda

I'm trying to pull the 'data-val' of a radio that has a specific class name.

I need it to: Find the data-val of the element within a radiogroup that has the class 'correct'

I cannot for the life of me think of how to do this. Any thoughts?

HTML

<fieldset>
    <input type='radio' name='rads1' id='x1' data-val='23' class='correct'/>
    <label for='x1'>#1</label><br/>
    <input type='radio' name='rads1' id='x2' data-val='46' class='incorrect'/>
    <label for='x2'>#2</label><br/>
    <input type='radio' name='rads1' id='x3' data-val='16' class='incorrect'/>
    <label for='x3'>#3</label><br/>
    <input type='radio' name='rads1' id='x4' data-val='52' class='incorrect'/>
    <label for='x4'>#4</label><br/>
</fieldset><br/>
<fieldset>
    <input type='radio' name='rads2' id='y1' data-val='3' class='incorrect'/>
    <label for='y1'>#1</label><br/>
    <input type='radio' name='rads2' id='y2' data-val='6' class='incorrect'/>
    <label for='y2'>#2</label><br/>
    <input type='radio' name='rads2' id='y3' data-val='36' class='correct'/>
    <label for='y3'>#3</label><br/>
    <input type='radio' name='rads2' id='y4' data-val='12' class='incorrect'/>
    <label for='y4'>#4</label><br/>
</fieldset>
È stato utile?

Soluzione

Try using the .data() method:

$('input[type=radio][name=rads1].correct').data('val');
// Or [name=rads2] depending on which one you want...

JSBin Demo

Altri suggerimenti

$('.correct').each(function() {
    console.log(  $(this).data('val'))
});

You would want to iterate over the elements as you might have multiple elements with same class.

Using map

var values = $('.correct').map(function() {
                return $(this).data('val');
            }).get();
console.log(values.join(','));

Check Fiddle

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top