Home > Software design >  on change event for several selects, some with multiple set
on change event for several selects, some with multiple set

Time:11-30

I have several selects, which all share the same class

$(".my-select").on("change", function() {
  console.log(this)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select >
  <option value="option1">1</option>
  <option value="option2">2</option>
  <option value="option3">3</option>
</select>

<select  multiple="multiple">
  <option value="option1">1</option>
  <option value="option2">2</option>
  <option value="option3">3</option>
</select>

However, the "on change" only gets fired when multiple is not set on the select.

What is the most efficient way, baring in mind I may have several selects on my page, some showing multiple others not, to get a change event? Vanilla JS or Jquery is fine.

CodePudding user response:

Please see the following example.

$(function() {
  $(".my-select").change(function() {
    console.log($(this).index(), $(this).val());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select >
  <option value="option1">1</option>
  <option value="option2">2</option>
  <option value="option3">3</option>
</select>

<select  multiple="multiple">
  <option value="option4">4</option>
  <option value="option5">5</option>
  <option value="option6">6</option>
</select>

<select >
  <option value="option7">7</option>
  <option value="option8">8</option>
  <option value="option9">9</option>
</select>

<select  multiple="multiple">
  <option value="option10">10</option>
  <option value="option11">11</option>
  <option value="option12">12</option>
</select>

This works as expected. Notice that multiple values are an Array of selected Values.

  • Related