2013-08-14 3 views
-1

вот мой exampleКак получить атрибут из элемента с jquery?

<fieldset data-role="controlgroup" id="test"> 
    <legend>Radio buttons, vertical controlgroup:</legend> 
    <input class="status" type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked"> 
    <label for="radio-choice-1">Cat</label> 
    <input class="status" type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2"> 
    <label for="radio-choice-2">Dog</label> 
    <input class="status" type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3"> 
    <label for="radio-choice-3">Hamster</label> 
    <input class="status" type="radio" name="radio-choice-1" id="radio-choice-4" value="choice-4"> 
    <label for="radio-choice-4">Lizard</label> 
</fieldset> 

$('.status').on("click", function() { 
    var inputs = $('#test').find('input'); 
    $.each(inputs, function (i, v) { 
     console.log(v); 
    }); 
}); 

я хотел бы получить id и val() всех радиокнопок, что-то вроде:

[{ 
    id: id1, 
    value: value1 
} { 
    id: id2, 
    value: value2 
}] 
... 

любые идеи?

ответ

1

Чтобы получить атрибут элемента, вы можете использовать .attr(), например $(el).attr('class').

Но чтобы получить желаемый результат в приведенном выше случае, вы можете использовать

$('.status').on("click", function() { 
    var array = $('#test').find('input').map(function(idx, el){ 
     return {id: el.id, value: el.value} 
    }).get(); 
    console.log(JSON.stringify(array)); 
}); 

Демо: Fiddle

1
$('.status').on("click", function() { 

var radioid = $(this).attr('id'); //gets the attribute ID of the clicked `.status` 
    radioval = $(this).val(); //gets the value of of the clicked `.status` 
alert('ID = ' + radioid + ' and VALUE = ' + radioval); //see the magic 


var inputs = $('#test').find('input'); 
$.each(inputs, function (i, v) { 
    console.log(v); 
}); 

});

Использование JQuery attr() получить идентификатор атрибута (и другие атрибуты) и val(), чтобы получить значение кнопки радио

DEMO

Смежные вопросы