Alan Pauil
Alan Pauil

Reputation: 209

How can remove read-only attribute from javascript

I have a checkbox in a span tag and input number. Initially the input number is read-only, When the checkbox is being ticked, remove the read only attribute of the Input number which is just close to checkbox. Here is my code. Any help would be appreciated

<tr>
    <td>
    <span><input type="checkbox"  asp-for="@Model.attendanceLogList[i].IsNormalAttendance" onclick="SetHrs(this);" /></span>
    <input type="number" readonly="readonly" placeholder="0.00" style="@(columnstyle);width: 5em"
                                       class="form-control format-text emphrs" asp-for="@Model.attendanceLogList[i].NormalHrs"  />
    </td>
</tr>
    <script>
     function SetHrs(element) {
            var rowIndex = $(element).closest("tr").attr('id');      
           if ($(element).is(":checked")) {
    $(this).closest('tr').find('input[type=number]').removeAttr('readonly');   //  Not working
                
            }
        }
    </script>

Upvotes: 0

Views: 365

Answers (1)

Sampgun
Sampgun

Reputation: 2977

I think you do more trouble than necessary to handle everything.

  1. Don't mix javascript and jQuery. Try to keep everything as tidy as possible, creating sort of controllers for your page blocks. For example here you could have a table controller
  2. It's a bit ugly trying to find elements by id, especially when using elements you expect to be repeated (such as rows). If you're sure that the input follows the span, you can use jQuery's next to get that element.

So in the following example what I did was:

  1. Attaching the event listener using event delegation (removed the onclick attribute from the checkbox)
  2. Getting the event target from the event argument
  3. Finding the readonly input, using the suggestion above
  4. Removing the readonly attribute, only when the checkbox is checked, so I did a little improvement, if you turn off the checkbox the readonly will be added again.

jQuery(function($) {
  $("table").on("change", "[name='foo']", function(e){
     const $target = $(e.target);
     const $targetInput = $target.parent().next();
     $targetInput[$target.is(":checked") ? "removeAttr" : "attr"]("readonly", "readonly");
  });
});
table {
  width: 100%;
  border: 1px solid #e2e2e2;  
}

input:read-only {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
  <tr>
  <td>
  <span>
    <input name="foo" type="checkbox" />
  </span>
  <input type="number" readonly="readonly" placeholder="0.00" />
  </td>
  </tr>
  </tbody>
</table>

Upvotes: 2

Related Questions