I'm using JQuery
on two input text elements (that are readonly
) and two buttons so that when button 1 is clicked only input 1 should become read/write. And, when button 2 is clicked, only input 2 should become read/write. And when the corresponding button is clicked again the corresponding input should become readonly again. But my following script changes the readonly attribute of both the inputs no matter which button is clicked. I thought only one event should be fired for that particular input as explained here by a user here
NOTE: I know we can use id instead of class selector but in my real scenario the input and buttons tags are generated dynamically via a loop and the data comes from a database. Hence, we don't know how many such element would be created each time. And, as the user in the above mentioned link pointed out only one click event should be fired for a corresponding button. So the Question is really how we can achieve that scenario since the example given below is not going to work in such a scenario.
HTML:
<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:
$(document).ready(function () {
$('.btnEdit').click(function () {
if ($('.txtInput').prop('readonly')) {
$('.txtInput').removeAttr('readonly');
}
else {
$('.txtInput').attr('readonly', 'readonly')
}
});
});
Page display: