Skip to content
Advertisement

How to get the changed select button among many select buttons?

I have many filter button like below, how can I get the select value without using its id?

<select name="selectId" id="selectId" multiple 
      class="selectpicker required form-control" data-live-search="true">
  <option value="All" selected>All</option>
  <option value="1" selected>1</option>
  <option value="2" selected>2</option>
  </select>
<select name="selectStore" id="selectStore" multiple 
      class="selectpicker required form-control" data-live-search="true">
  <option value="All" selected>All</option>
  <option value="A" selected>Store A</option>
  <option value="B" selected>Store B</option>
</select>
<select name="selectProduct" id="selectProduct" multiple 
      class="selectpicker required form-control" data-live-search="true">
  <option value="All" selected>All</option>
  <option value="apple" selected>Apple</option>
  <option value="orange" selected>Orange</option>
</select>

Normally, I will use this code to find the changed select button:

$(document).ready(function() {
    // Get filter function for chart
    $('#selectId').change(function() {
        var select = $("#selectId").val();

        if (selectLength >= 1 && select.includes("All")) {
            $('.selectpicker#selectId').selectpicker('deselectAll');
            makeChart();
        }
        else {
            makeChartFilter(select);
        }
    })
});

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:

$(document).ready(function() {
    // Get filter function for chart
    $('#selectpicker').change(function() {
        id_change = something;
        var select = $("#id_change").val();
        ...
    })
});

Advertisement

Answer

Using vanilla JavaScript and the eventTarget, this is relatively straight forward. Here is an example:

document.getElementById('container').onchange = ({ target }) => {
  console.log(target.value);
};
<form id="container">
<select name="foo">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>
<select name="bar">
  <option>a</option>
  <option>b</option>
  <option>c</option>
</select>
</form>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement