3

I have to toggle the readonly property on a table using a checkbox,more precisely,I'm fetching the table from the database and I create in every row a checkbox,this checkbox should toggle the readonly property on its row,and only there. I thought then that I could make a class="row_'.index.'" and attach it to every row of the autogenerated table,but then I don't know how to do pass that class in jQuery to make the function that toggles the readonly...is there an easier,cleaner way of doing this?

Fergant
  • 81
  • 1
  • 9
  • 1
    A readonly property can't be set on ``. do you mean inside ``s or `
    – Accountant م Sep 13 '19 at 08:41
  • Yes,I was meaning that the table,is generated with tags in every cell,, I have no problem toggling every readonly with a functions,but how to I toogle the elements in that specific ,row, where the checkbox is? I can pass with php,an index to a class when I create the row,so that every row has a different number on that class,like the first class would have "class="row_1"" and then the second row "class="row_2"" and so goin on...but in jQuery I can't select the checkbox and the class by writing $(".checkbox_'.index.'") – Fergant Sep 13 '19 at 08:50
  • 1
    Forget about PHP, this is a client side problem, please include in the question the HTML of a `` including that checkbox and the input elements. – Accountant م Sep 13 '19 at 08:58

2 Answers2

1

You could iterate through the checkboxes on the page then navigate to the tr property from there? It's hard to understand without any code samples though, and I'm too new to SO to comment.

 var inputs = form.getElementsByTagName("input");

 for (var i = 0; i < inputs.length; i++) {
   if ($(inputs[i]).type == "checkbox" && $(inputs[i]).is(':checked')){
     $(inputs[i]).closest('tr').prop('readonly', true);
   }
 }

Probably too verbose and probably going to get hounded, but I thought it might help!

eponini
  • 74
  • 1
  • 13
1

I will bind a function to the checkbox then inside this function you will find the closest parent<tr> and make every child <input> in that <tr> readonly if the checkbox is checked (Don't worry about the checkbox <input> itself you will still be able to uncheck them again. More on this)

Try this snippet

$("table input.makeReadOnly").change(function (){
    if($(this).prop("checked")){
       $(this).closest("tr").find("input").prop("readonly", true);
    } else {
       $(this).closest("tr").find("input").prop("readonly", false);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
        <td><input></td>
        <td><input></td>
        <td><input class="makeReadOnly" type="checkbox"></td>
    </tr>
    <tr>
        <td><input></td>
        <td><input></td>
       <td><input class="makeReadOnly" type="checkbox"></td>
    </tr>
  </tbody>
</table>
Accountant م
  • 6,975
  • 3
  • 41
  • 61