使用Javascript验证多选单选按钮

时间:2015-05-10 11:23:52

标签: javascript validation radio-button

如果未从该广播组中选中回答(单选按钮),我想阻止提交表单(带有id =“new_question”)。

<input class="radioclass" id="q1a" value="a" name="question[q1correct]" type="radio">
<input class="radioclass" id="q1b" value="b" name="question[q1correct]" type="radio">
<input class="radioclass" id="q1c" value="c" name="question[q1correct]" type="radio">
<input class="radioclass" id="q1d" value="d" name="question[q1correct]" type="radio">
<input id="publishbtn" class="greenbtn" type="submit" value="PUBLISH" name="commit"></input>

有十个广播组(上面的html相同)需要检查一个答案。
表单ID为“new_question”

因此,除非检查所有答案,否则需要帮助进行不允许提交表单的验证。

到目前为止我所拥有的:

validateForm = function() {
x = document.forms['new_question']['question[q1correct]'].value;
if (x === null || x === '') {
  alert('Name must be filled out');
return false;
 }
};

我确实需要这10个无线电组的其余部分,但我想一旦我知道如何在一个,我可以在所有无线电组上实现代码。

1 个答案:

答案 0 :(得分:0)

假设那种html:

<form id="foo">
    <div class='selectGroup'>
        <input class="radioclass" id="q1a" value="a" name="question[q1correct]" type="radio">1</input>
        <input class="radioclass" id="q1b" value="b" name="question[q1correct]" type="radio">2</input>
        <input class="radioclass" id="q1c" value="c" name="question[q1correct]" type="radio">3</input>
        <input class="radioclass" id="q1d" value="d" name="question[q1correct]" type="radio">4</input>

    </div>

    <div class='selectGroup'>
        <input class="radioclass" id="q2a" value="a" name="question[q2correct]" type="radio">1</input>
        <input class="radioclass" id="q2b" value="b" name="question[q2correct]" type="radio">2</input>
        <input class="radioclass" id="q2c" value="c" name="question[q2correct]" type="radio">3</input>
        <input class="radioclass" id="q2d" value="d" name="question[q2correct]" type="radio">4</input>

    </div>

    <input id="publishbtn" class="greenbtn" type="submit" value="PUBLISH" name="commit">

        </input>
</form>

您可以使用以下js

$('#foo').submit(function(e) { 
    e.preventDefault();

    var $form = $(e.currentTarget)
    var groupsValidationList = []

    selectGroups = $form.children('.selectGroup')

    selectGroups.each(function(index, group) {
      $group = $(group);

        checks = $group.children('.radioclass').map(function(index, radioItem) { 

            return $(radioItem).is(':checked')
        })
         isValid = ($.inArray(true, checks) != -1);

         groupsValidationList.push(isValid);
    })

    if(groupsValidationList.every(function(validationResult) { return validationResult; }))             {
        alert('ok');
    } else {
         alert('at least one group is not marked');   
    }


})

https://jsfiddle.net/4qwvgqkz/