Search code examples
javascriptradio-button

attr() on radio return: undefined is not a function


I have this code

$.each($('input:checked', '#components-holder'), function(index, input){
    console.log(input.attr('value'));
});

And I got this error:

undefined is not a function

How can I iterate on all radio in my page and got value ?


Solution

  • The object sent to your callback as input is not a jQuery object, so you can't use jQuery methods. You need to convert it into a jQuery object to use jQuery methods:

    console.log($(input).attr('value'));
    

    Or use a native DOM property:

    console.log(input.value);
    

    Or, you may wish to use map to get the appropriate values:

    var values = $('#components-holder input:checked').map(function(index, input) {
        return input.value;
    }).get();
    

    values is now an array containing all the relevant values.