允许只检查测试里面的一个复选框

时间:2017-06-13 09:01:22

标签: jquery loops checkbox

我有一个while循环,我从数据库中获取数据:

while($row = mysqli_fetch_array($skillsResult))
{    

    $id = $row['id'];
    $driver = $row['driver'];
    $subdriver = $row['subdriver'];
    $dep = $row['department'];
    $skill = $row['skills'];
    $vrgood = $row['4'];
    $good = $row['3'];
    $middle = $row['2'];
    $low = $row['1'];
?>

<br/><br/>
<fieldset>
<legend id="q1" class="desc notranslate">
   <?php echo $no++; ?> 
</legend>
<div class="full_qst">
    <div class="drvr"> <?php echo $driver; ?> </div><span class="divider">|</span>
    <div class="sbd_drvr"> <?php echo $subdriver; ?> </div><span class="divider">|</span>
    <div class="qst"> <?php echo $skill; ?> </div>

    <div class="mrk">
        <span>
            <label class="choice" for="q1_a" >
            <input class="q" name="q1_a[]" type="checkbox" value="<?php echo $low ?>"   />
            1</label>
        </span>
        <span>
            <label class="choice" for="q1_a" >
            <input class="q" name="q1_a[]" type="checkbox" value="<?php echo $middle ?>"    />
            2</label>
        </span>   
        <span>
            <label class="choice" for="q1_a" >
            <input class="q" name="q1_a[]" type="checkbox" value="<?php echo $good ?>"   />
            3</label>
        </span>    
        <span>
            <label class="choice" for="q1_a" >
            <input class="q" name="q1_a[]" type="checkbox" value="<?php echo $vrgood ?>"    />
            4</label>
        </span>
    </div> 
</div>
</fieldset>
<?php
$count++;
}

我得到了大约15条记录。我想要的是允许用户单独选中每行的复选框,并允许它们仅检查同一行上的框。 所以不是这样的: enter image description here

我希望得到这个:enter image description here

我试图实现这个:

$('.mrk input#q').on('change', function() { 
    if($(this).is(':checked')){
        $(':checkbox[name="'  + $(this).prop('name') + '"]').not($(this)).prop('checked',false);
    }
});

但它取消选择上面一行的前一个框,并允许我在整页中只选择一个复选框。有办法解决吗?

2 个答案:

答案 0 :(得分:1)

您的代码工作正常,只需用类$('input.q')

替换选择器

但是,对于所有复选框,每个行只允许选择一个具有相同名称的复选框,则需要使用以下代码,这将取消选中同一div内的所有复选框,然后检查更改后的复选框。

$('input.q').on('change', function() { 
    $(this).parents('.full_qst').find(".q[name='"+$(this).attr("name")+"']").not(this).prop('checked',false); 
});

答案 1 :(得分:0)

您可以对该作业使用.siblings()功能,并且永远不要在dom元素的同一页面上使用相同的ID。它只获得你的第一个身份,而且看不到别人。

$('.mrk input').on('change', function() { 
    if($(this).is(':checked')){
      $(this).siblings('input').prop('checked',false);
    }else
      $('.mrk input').prop('checked',false);
});

如果您不需要检查是否选中了这个,您甚至可以使用

$('.mrk input').on('change', function() {
      $(this).siblings('input').prop('checked',false);
});