启用/禁用基于单选按钮的功能按钮

时间:2011-06-15 22:10:31

标签: javascript jquery

当页面加载带有单选按钮的表格时。在表3下面,按钮X,Y,Z被禁用。当用户只从表中选择一个单选按钮时,应该启用这三个按钮X,Y,Z?

2 个答案:

答案 0 :(得分:4)

使用Javascript:

$('table input[type="radio"]').click(function() {
    $('input[type="button"]').removeAttr('disabled');
});

HTML:

<table>
    <tr>
        <td><input type="radio" />...
...

<input type="button" disabled ... />

答案 1 :(得分:0)

可以将监听器附加到表,并且可以按名称引用单选按钮组。当表格中的单选按钮发生单击事件时,可以根据是否选中特定组中的任何按钮来启用或禁用X,Y和Z按钮。逻辑需要允许重置表单的情况,例如

<form>
  <table id="table0" style="border: 1px solid black;">
    <tr>
      <td><input type="radio" name="group1">
      <td><input type="radio" name="group1">
      <td><input type="radio" name="group1">
    <tr>
      <td><input type="reset">
      <td>
      <td>
  </table>
  <label for="r2-0">X&nbsp;<input type="radio" name="group2" id="r2-0" value="x"></label>
  <label for="r2-1">Y&nbsp;<input type="radio" name="group2" id="r2-1" value="y"></label>
  <label for="r2-2">Z&nbsp;<input type="radio" name="group2" id="r2-2" value="z"></label>
</form>

<script type="text/javascript">
function enableButtons() {
  var buttons1 = document.getElementsByName('group1');
  var buttons2 = document.getElementsByName('group2');
  var checkedState = false;

  // Check if any buttons in group 1 have been checked
  for (var i=0, iLen=buttons1.length; i<iLen; i++) {
    if (buttons1[i].checked) {
      checkedState = true;
      break;
    }
  }

  // Enable or disable group 2 buttons based on above result
  // When disabling, also uncheck any that are checked
  for (var j=0, jLen=buttons2.length; j<jLen; j++) {
    if (!checkedState) {
      buttons2[j].checked = false;
      buttons2[j].disabled = true;
    } else {
      buttons2[j].disabled = false;
    }
  }
}

window.onload = function() {

  // Disable X, Y & Z buttons
  var buttons = document.getElementsByName('group2');
  for (var i=0, iLen=buttons.length; i<iLen; i++) {
    buttons[i].disabled = true;
  }

  // Add onlick listener to table
  var table  = document.getElementById('table0');
  if (table) table.onclick = function() {
    window.setTimeout(enableButtons, 1);
  }
}

</script>