使用另一个单选按钮启用单选按钮

时间:2014-03-01 07:29:55

标签: javascript html

如何在选择父级单选按钮时启用子单选按钮?

<body>
  <p>
    <input type="radio" id="bdmain" name="educationalqualification" disabled="true" /> Bachelor's Degree
  </p>
  <ul>
    <li>
       <label>
          <input type="radio" name="bd" disabled="true"/>
                Four Years
       </label>
   </li>
   <li>
      <label>
         <input type="radio"name="bd" disabled="true"/>
                Exceeding Four Years
      </label>
  </li>
  </ul>
</body>

4 个答案:

答案 0 :(得分:0)

尝试,

$("#bdmain").parent().next("ul").find("input[type='radio']").each(function(){
 $(this).removeAttr("disabled");
});

答案 1 :(得分:0)

您必须从父按钮中删除disabled="true"(我还添加了标签)

<body>
  <p>
      <label for="bdmain">
          <input type="radio" id="bdmain" name="educationalqualification" />
          Bachelor's Degree
      </label>
  </p>
  <ul>
    <li>
        <label>
            <input type="radio" name="bd" class="bdmain-child" disabled="true"/>
            Four Years
        </label>
    </li>
    <li>
        <label>
            <input type="radio"name="bd" class="bdmain-child" disabled="true"/>
            Exceeding Four Years
        </label>
      </li>
  </ul>
</body>

假设您可以使用jQuery:

$(function() {
    // select by name to handle disabling the button if the radio is deselected
    $("[name='educationalqualification']").click(function(e) {
        // enable/disable child items if parent is not checked
        $(".bdmain-child").prop("disabled", !$('#bdmain').is(':checked'));        
    });
});

JSFiddle Sample

答案 2 :(得分:0)

为了启用/禁用子元素,必须启用父元素。 尝试使用启用了父级的代码,单击该代码时,将启用其子级无线电元素。

<html>
<head>
<script type='text/javascript'>
function enableChildren() {
  var bdEls = document.getElementsByName('bd');
  for(var i=0;i<bdEls .length;i++)
    bdEls[i].disabled=false;
  }
}
</script>
</head>

<body>
<p><input type="radio" name="educationalqualification" onClick="enableChildren()"  id="bdmain"/>Bachelor's Degree</p>

<label><input type="radio" name="bd"  disabled="true"/>Four Years</label></li>
<label><input type="radio" name="bd"  disabled="true"/>Exceeding Four Years</label></li>

</body>
</html>

答案 3 :(得分:0)

您有单选按钮,因此我假设有多个父子组需要正常运行。幸运的是你没有标记jQuery所以这是一个很好的练习,不要忘记javascript:

var parentChecks = document.getElementsByName('educationalqualification');

for (var i = 0; i < parentChecks.length; i++ ) {
    parentChecks[i].addEventListener('change', function(e) {
        for (var j = 0; j < parentChecks.length; j++) {
            var radio = document.querySelectorAll('#' + parentChecks[j].dataset.group + ' input[type=radio]');
            for (var k = 0; k < radio.length; k++) {
                radio[k].disabled = !parentChecks[j].checked;
                if (!parentChecks[j].checked) {
                    radio[k].checked = false;
                }
            }    
        } 
    }, false);
}

演示:http://jsfiddle.net/Q9PZF/