I have many filter button like below, how can I get the select value without using its id
?
JavaScript
x
19
19
1
<select name="selectId" id="selectId" multiple
2
class="selectpicker required form-control" data-live-search="true">
3
<option value="All" selected>All</option>
4
<option value="1" selected>1</option>
5
<option value="2" selected>2</option>
6
</select>
7
<select name="selectStore" id="selectStore" multiple
8
class="selectpicker required form-control" data-live-search="true">
9
<option value="All" selected>All</option>
10
<option value="A" selected>Store A</option>
11
<option value="B" selected>Store B</option>
12
</select>
13
<select name="selectProduct" id="selectProduct" multiple
14
class="selectpicker required form-control" data-live-search="true">
15
<option value="All" selected>All</option>
16
<option value="apple" selected>Apple</option>
17
<option value="orange" selected>Orange</option>
18
</select>
19
Normally, I will use this code to find the changed select button:
JavaScript
1
15
15
1
$(document).ready(function() {
2
// Get filter function for chart
3
$('#selectId').change(function() {
4
var select = $("#selectId").val();
5
6
if (selectLength >= 1 && select.includes("All")) {
7
$('.selectpicker#selectId').selectpicker('deselectAll');
8
makeChart();
9
}
10
else {
11
makeChartFilter(select);
12
}
13
})
14
});
15
But the problem is when there are many filter buttons, I have to write many functions like above and just only change the id
.
How can I just use something like this:
JavaScript
1
9
1
$(document).ready(function() {
2
// Get filter function for chart
3
$('#selectpicker').change(function() {
4
id_change = something;
5
var select = $("#id_change").val();
6
7
})
8
});
9
Advertisement
Answer
Using vanilla JavaScript and the eventTarget, this is relatively straight forward. Here is an example:
JavaScript
1
3
1
document.getElementById('container').onchange = ({ target }) => {
2
console.log(target.value);
3
};
JavaScript
1
12
12
1
<form id="container">
2
<select name="foo">
3
<option>1</option>
4
<option>2</option>
5
<option>3</option>
6
</select>
7
<select name="bar">
8
<option>a</option>
9
<option>b</option>
10
<option>c</option>
11
</select>
12
</form>