So I created an html-table with a for loop containing a list of objects from my python application. I now want to implement a delete function and for that I need to get the values of the cells from the same row where the button was clicked. I would prefer to do it in JavaScript, not jquery as I don't have any experience with that
<table class="table" id="table">
<tr>
<th scope="col">#</th>
<th scope="col">Titel</th>
<th scope="col">Interpret</th>
</tr>
{% for song in songs %}
<tr>
<td>{{song.id}}</td>
<td>{{song.titel}}</td>
<td>{{song.interpret}}</td>
<td>
<button class="btn btn-danger" type="submit" id="delete_button" name="delete_button" onclick="get_values(this)">Delete</button>
</td>
</tr>
{% endfor %}
</table>
EDIT:
I looked up those .parentNode and .previousSibling @Barmar mentioned and tried to write a function for the existing onclick="get_values(this)" I already added to the buttons above
<script>
function get_values(this) {
var td = this.parentNode;
var x = td.previousSibling.innerHTML;
console.log(x);
}
</script>
The console.log response said: "ReferenceError: Can't find variable: get_values"
EDIT 2:
So I finally made progress with avoiding the ReferenceError. I was trying function get_values(this) which wasn't allowed, so I changed it to function get_values(x).
<script>
function get_values(x) {
var td = x.parentNode;
interpret = td.previousSibling;
interpret_value = interpret.innerHTML;
titel = interpret.previousSibling.previousSibling.innerHTML;
console.log(titel);
console.log(interpret_value);
}
</script>
</body>
The problem I now have is that the code actually actually works without the .innerHTML properties. So I am actually getting back e.g. last Christmas and wham!. But now I struggle with just getting the values without the td-tags. I tried it with .value aswell.
EDIT 3:
Okay, I guess there's been a little mistake, I sorted it out by myself now, here's the code I am using now and it gives me the correct values. I still don't really get why I need to use the double .previousSibling but aslong as it works, I'm fine. Thanks to everyone who tried to help, I really appreciate that. I wish you guys a Happy New Year.
<script>
function get_values(x) {
var td = x.parentNode;
interpret = td.previousSibling.previousSibling;
interpret_value = interpret.innerHTML;
titel = interpret.previousSibling.previousSibling;
titel_value = titel.innerHTML;
console.log(interpret);
console.log(interpret_value);
console.log(titel);
console.log(titel_value);
}
</script>