Search code examples
jqueryhtmlcheckboxdisabled-input

How to disable input fields per row if its checkbox is checked?


I couldn't find a solution to my particular problem, although there were a lot of topics about similar issues.

My code disables all the fields my table contains instead of disabling only a row per checked checkbox.

  <tr>
    <td><input type="text" name="pageName[]"></td>
    <td>
      <select name="pageSelection[]">
        <option selected>-- Select --</option>
        <option>...</option>
      </select>
    </td>
    <td>
      <input type="text" name="pageData[]">
    </td>
    <td>
      <input type="checkbox" name="disableRow[]">
    </td>
  </tr>
  <tr>
    <td><input type="text" name="pageName[]"></td>
    <td>
      <select name="pageSelection[]">
        <option selected>-- Select --</option>
        <option>...</option>
      </select>
    </td>
    <td>
      <input type="text" name="pageData[]">
    </td>
    <td>
      <input type="checkbox" name="disableRow[]">
    </td>
  </tr>

My jQuery code:

$("input:checkbox[name^='disableRow']").on("click", function(){
      $("table tr input:text, table tr select").prop("disabled", this.checked);
});

I unluckily tried to concatenate the code below:

.has("input:checkbox(:checked)")

Solution

  • Currently your code says that every input within the table should be disabled. You have to narrow it down to the parent.

    Edit: Added a line which disables the checkboxes on default and switched from click to change.

    $("input:checkbox[name^='disableRow']").prop("checked", false);
    
    $("input:checkbox[name^='disableRow']").on("change", function(){
          $(this).closest("tr").find("input:text, select").prop("disabled", this.checked);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
       <tr>
          <td><input type="text" name="pageName[]"></td>
          <td>
            <select name="pageSelection[]">
              <option selected>-- Select --</option>
              <option>...</option>
            </select>
          </td>
          <td>
            <input type="text" name="pageData[]">
          </td>
          <td>
            <input type="checkbox" name="disableRow[]">
          </td>
        </tr>
        <tr>
          <td><input type="text" name="pageName[]"></td>
          <td>
            <select name="pageSelection[]">
              <option selected>-- Select --</option>
              <option>...</option>
            </select>
          </td>
          <td>
            <input type="text" name="pageData[]">
          </td>
          <td>
            <input type="checkbox" name="disableRow[]">
          </td>
        </tr>
     </table>