So in this case I am trying to get the id of the element with id="current1".
$(document).ready(function() {
$(".testbutton").on('click', function() {
var num2 = $(this).prev().val();
var ID2 = $(this).prev().attr("id");
var ID1 = $(this).prevAll().attr("id");
document.write(num2);
document.write("ID2=" + ID2);
document.write("ID1=" + ID1);
});
});
.testbutton {
background-color: #ff7b00;
color: white;
border-radius: .2em;
padding: .1em .2em;
margin-top: 2em;
border: none;
cursor: pointer;
width: 5em;
font-size: .9em;
}
.testbutton:hover {
background-color: #924701;
}
.numberinput {
width: 3em;
text-align: center;
}
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr id="row1">
<td class="faction">Testrow</td>
<td><a class="currentamount" id="current1" value="0">0</a></td>
<td><input type="number" id="num1" class="numberinput" placeholder="0"></input><a type="button" class="testbutton" id="add1">get previous</a></td>
<td></td>
</tr>
>Solution :
.prev() and .prevAll() only return siblings, but #current1 is not a sibling of .testbutton, since they’re in different <td>.
You need to go up a level and get the sibling of the parent.
$(document).ready(function() {
$(".testbutton").on('click', function() {
var num2 = $(this).closest("td").prev().find(".currentamount").attr("id");
console.log(num2);
});
});
.testbutton {
background-color: #ff7b00;
color: white;
border-radius: .2em;
padding: .1em .2em;
margin-top: 2em;
border: none;
cursor: pointer;
width: 5em;
font-size: .9em;
}
.testbutton:hover {
background-color: #924701;
}
.numberinput {
width: 3em;
text-align: center;
}
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr id="row1">
<td class="faction">Testrow</td>
<td><a class="currentamount" id="current1" value="0">0</a></td>
<td><input type="number" id="num1" class="numberinput" placeholder="0"><a type="button" class="testbutton" id="add1">get previous</a></td>
<td></td>
</tr>
</table>