Currently, I am utilizing JQuery with two input text elements (set as readonly) and two buttons. The goal is for only input 1 to become read/write when button 1 is clicked, and for only input 2 to become read/write when button 2 is clicked. If the corresponding button is clicked again, the corresponding input should revert back to being readonly. However, my current script changes the readonly attribute of both inputs regardless of which button is clicked. According to some user suggestions on Stack Overflow, only one event should be fired for each specific input element.
Please Note: Although using an id instead of a class selector can be a solution, in my case the input and button tags are generated dynamically through a loop using data from a database. Therefore, the number of elements created each time is unknown. Following the feedback provided by the user mentioned earlier, we need to figure out how to achieve this functionality within such a dynamic scenario since the example provided below may not work as intended in this context.
HTML Example:
<table>
<tbody>
<tr>
<td>
<input class="txtInput" type="text" name="test1" value="test1val" readonly/>
</td>
<td>
<input type="button" class="btnEdit" name="editName" value="Edit"/>
</td>
</tr>
<tr>
<td>
<input class="txtInput" type="text" name="test2" value="test2val" readonly />
</td>
<td>
<input type="button" class="btnEdit" name="editName" value="Edit" />
</td>
</tr>
</tbody>
</table>
JQuery Functionality:
$(document).ready(function () {
$('.btnEdit').click(function () {
if ($('.txtInput').prop('readonly')) {
$('.txtInput').removeAttr('readonly');
}
else {
$('.txtInput').attr('readonly', 'readonly')
}
});
});
Page Preview: