У меня есть переключатели:
<input type="radio" value="a" name="questions[0]">
<input type="radio" value="b" name="questions[0]">
<input type="radio" value="c" name="questions[0]">
<input type="radio" value="d" name="questions[0]">
<input type="radio" value="a" name="questions[1]">
<input type="radio" value="b" name="questions[1]">
<input type="radio" value="c" name="questions[1]">
<input type="radio" value="d" name="questions[1]">
Как это сделать с помощью jQuery? Я хочу подтвердить, что ответ был дан для каждого вопроса. Благодарю.
edit: или есть даже способ получить длину массива вопросов?
$("#myForm input[type=radio]").each(function() {
//whatever you need
});
$('[name="questions[1]"]:checked').val()
дает проверенное значение вопроса 1.
Или, как показано ниже, получите проверенное значение с именем:
$('input[type=radio]:checked').each(function() {
console.log($(this).val(), $(this).attr('name'));
});
Вы можете сделать что-то вроде этого:
var rgroups = [];
$('input:radio').each(function (index, el) {
var i;
for (i = 0; i < rgroups.length; i++)
if (rgroups[i] == $(el).attr('name')) return true;
rgroups.push($(el).attr('name'));
});
rgroups = rgroups.length;
$('#test').click(function () {
if ($('input:radio:checked').length < rgroups) alert('You must fill in all the fields.');
else alert("You're done!");
});
$this.attr('name')
в цикле.