Pavel Marian Pavel Marian - 3 months ago 9
jQuery Question

Changing attr not workins as expected

I apology for the title of this question, I know it should be explicit but I don't really know why this problem occurs.
I made the following example to describe my problem:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<table>
<tr>
<td>
<button id="arm" disabled>Arm</button>
</td>
<td>
<button id="disarm">Disarm</button>
</td>
</tr>
</table>

<script>
$("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>
</body>
</html>


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
.

Any ideea what I am doing wrong ?

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 :)