Javascript检查单选按钮

Javascript checking radiobuttons

本文关键字:单选按钮 检查 Javascript      更新时间:2023-09-26

我得到了这个代码

    <?php foreach($this->question as $question): ?>
<div class="question">
    <?php echo $question['question'] ?>          </div>

<?php if($this->activeEdition["id"]!=20) { ?>
<div class="answerswers">
    <?php
    $i = 1;
    foreach($question['answers'] as $answer):
    ?>
    <input type="radio" name="question[<?php echo $question['id'] ?>]" value="<?php echo $answer['id'] ?>" id="<?php echo
           $answer['id']
    ?>" class="radio_answer radio_answer_<?php echo $i; ?>" >
    <label for="<?php echo $answer['id'] ?>"><?php echo $answer['answer'] ?></label>
    <?php
    if(count($question['answers']) > 3){
    echo '<br/>';
    }
    ?>
<?php
$i++;
endforeach;
?>
</div>

如果每个问题中都有一个单选按钮被选中,如何在javascript中以简单明了的方式进行检查?

如果所有答案都是必需的,那么在生成答案时,应该将每个答案中的第一个单选设置为选中。这是最简单的方法。

当然,你可以用JS来检查它,但它会很难看。这是一个演示代码:

<script>
    function check(){
        var inputs = document.getElementsByTagName('input');
        var names = [];
        var checked = 0;
        for(var i=0;i<inputs.length;i++){
            if(inputs[i].type=='radio'){
                inArray = false;
                for(var j=0;j<names.length;j++){
                    if(names[j]==inputs[i].name){
                        inArray = true;
                        break;
                    }
                }
                if(!inArray){
                    names.push(inputs[i].name);
                }
                if(inputs[i].checked){
                    checked++;
                }
            }
        }
        return names.length==checked;
    }
</script>
<input type="radio" name="a">
<input type="radio" name="a"><br/>
<input type="radio" name="b">
<input type="radio" name="b"><br/>
<input type="radio" name="b">
<input type="radio" name="c">
<input type="radio" name="c"><br/>
<input type="radio" name="d">
<input type="radio" name="d">
<input type="radio" name="d">
<input type="button" onClick="alert(check());">

如果你知道问题的数量,你可以简化它,也许有更好的解决方案来检查数组。

有了jQuery就更好了。

ok我使用jQuery 做了更好的解决方案

<script type="text/javascript">
function checkform()
{
    var ilosc = document.getElementsByClassName('question');
    var n = $("input:checked").length;
    if (n != ilosc.length)
    {
    alert('Proszę zaznaczyć wszyskie odpowiedzi');
    return false;
    }else return true;
}
</script>