Pavel Marian Pavel Marian - 3 months ago 8
Javascript Question

Changing attribute not working as expected

I made the following example to describe my problem:



$("tr > td > #arm").on("click", function() {
$(this).parent().children("#arm").prop("disabled", true);
$(this).parent().children("#disarm").prop("disabled", false);
});

$("tr > td > #disarm").on("click", function() {
$(this).parent().children("#arm").prop("disabled", false);
$(this).parent().children("#disarm").prop("disabled", true);;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<table>
<tr>
<td>
<button id="arm" disabled>Arm</button>
</td>
<td>
<button id="disarm">Disarm</button>
</td>
</tr>
</table>

<script>
</script>





I have the above
table
with one
row
that contains 2
cells
and a
button
in each
cell
. One of them is
disabled
so I made a script where when I press the second
button
it should enable the first one and disable the one which was clicked.

Disabling the
button
that was clicked work as I expected but I don't know why it doesn't enable the other
button
.

Answer

You're not selecting the right element. Your code is

$(this).parent().children("#disarm")

where $(this) is the #arm element, then parent() is the td cell.

So basically you're searching for a children element (#disarm) of that cell, that's why he can't find it

Try with this instead

$("tr > td > #arm").on("click", function() {
    $(this).prop("disabled", true);
    $(this).closest("tr").find("#disarm").prop("disabled", false);
});

$("tr > td > #disarm").on("click", function() {
    $(this).closest("tr").find("#arm").prop("disabled", false);
    $(this).prop("disabled", true);
}); 

Here it is a WORKING DEMO of your code :)

Comments