I’ve got an Table with a <td>
that is housing an <select>
with <options>
.
I want to create a request to my Django backend with the value of the Option clicked and the hostname in the row of the clicked <option>
.
My JavaScript can show the value of the <option>
but I dont know how to access the hostname.
$(function (e) {
$(".form-select").change(function (event) {
alert(this.value); //shows the Value of the selected Option
for(var i = 0; i < this.options.length; i++){ //deselect the option
this.options[i].selected = false;
}
});
});
<table class="table">
<thead>
<tr>
<th scope="col">Hostname</th>
<th scope="col">User</th>
<th scope="col">Vulnerabilites</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Rechnernummer"><a href="javascript:void(0)" class="link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover" onclick="clientInfo(event);">Host001</a></td>
<td class="User">User001</td>
<td class="Vulnerabilites">
<select class="form-select" size="4">
<option value="2705">Security Vulnerability CVE-2018-1285 for log4net</option>
<option value="73562">Security Vulnerability CVE-2022-39427 in VirtualBox</option>
</select>
</td>
</tr>
<tr>
<td class="Rechnernummer"><a href="javascript:void(0)" class="link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover" onclick="clientInfo(event);">Host002</a></td>
<td class="User">User002</td>
<td class="Vulnerabilites">
<select class="form-select" size="4">
<option value="68069">Security Vulnerability CVE-2021-34803 for TeamViewer</option>
<option value="74465">Security Vulnerability CVE-2023-21899 in VirtualBox</option>
</select>
</td>
</tr>
</tbody>
</table>
2
Answers
You can "traverse the DOM" from the "current" element in the event handler, up to a common parent, and back down to the "neighboring" element that you’re looking for. For example:
The use of
.closest()
selects the first matching parent element (traversing "up" the DOM) and then.find()
selects a matching element within that element (traversing back "down" the DOM).You can access the selected option text with
.text()
function as