doujun5009 2016-08-27 17:10
浏览 50

如何使用javascript取消选中数组中的单选按钮

How do I un check a radio button within the input box. I've been trying to uncheck this radio button with javascript but I can't seem to be able to do it when its inside an array

this is the code that I want to un check with javascript

<?php
    for($i = 0; $i < 3; $i ++){
        $num = rand(0,2);
        for($j = 0; $j < 3; $j++){
            if($num){
                $check = 'checked';
            }else
                $check='';
            echo '<input name="acc['.$i.']" type="radio" '.$check.'>';
        }
        echo '<br/>';

    }
?>

I've tried with this javascript but I don't know how to point to the actual radio button to uncheck

$(':radio').mousedown(function(e){
    var $self = $(this);
    if( $self.is(':checked') ){
        var uncheck = function(){
            setTimeout(function(){
                $self.removeAttr('checked');
            },0);
        };
        var unbind = function(){
            $self.unbind('mouseup',up);
        };
        var up = function(){
            uncheck();
            unbind();
        };
        $self.bind('mouseup',up);
        $self.one('mouseout', unbind);
    }
});
  • 写回答

1条回答 默认 最新

  • dongmei2351 2016-08-27 19:02
    关注

    So you have some rows, each row has 3 radios.

    • One radio can be togglable
    • If a user selects a radio in one row, all radios from other rows should become "unchecked":

    var $radios = $(":radio");
    
    $radios.on("mouseup", function(e) {
    
      var name  = $(this).prop("name");
    
      // Make togglable
      if(this.checked){
        setTimeout($.proxy(function() {
          this.checked = false;
        }, this),0);
      }
      
      // Unselect radios of other rows
      $radios.not( $("[name='"+ name +"']") ).prop("checked", false);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <br>A
    <input type="radio" name="acc[0]">
    <input type="radio" name="acc[0]">
    <input type="radio" name="acc[0]">
    
    <br>B
    <input type="radio" name="acc[1]">
    <input type="radio" name="acc[1]">
    <input type="radio" name="acc[1]">
    
    <br>C
    <input type="radio" name="acc[2]">
    <input type="radio" name="acc[2]">
    <input type="radio" name="acc[2]">

    (Note that your PHP currently makes checked all three radios inside a row! use Inspect Element to see that issue. You should fix this; but I have no clue why you use random 0,1,2... anyways so I'm unable to help you here)

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站