开发者

enable/disable functionality buttons based on radio button

开发者 https://www.devze.com 2023-03-13 02:40 出处:网络
When the page loads a table with radio buttons is displayed. below the table 3 buttons X, Y, Z are disabled. When the user开发者_高级运维 selects a radio button from the table only then these three bu

When the page loads a table with radio buttons is displayed. below the table 3 buttons X, Y, Z are disabled. When the user开发者_高级运维 selects a radio button from the table only then these three buttons X, Y, Z should be enabled?


Javascript:

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

HTML:

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

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


A listener can be attached to the table and the radio button set can be referenced by name. When a click event occurs on a radio button in the table, the X, Y and Z buttons can be enabled or disabled based on whether any buttons in a particular group are checked or not. The logic needs to allow for cases where the form is reset, e.g.

<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号