Home > Enterprise >  Select OnChange same value twice
Select OnChange same value twice

Time:04-02

I have a selectbox which adds articles to a list with jQuery like this:

$('#articles').on('change', function(e) {
    //adds article to list
}

This works fine, but when I try to add the same article twice, the onChange method does not fire since it is selected already.

What would be the nicest way to solve this problem?

I do not want to deselect it since it shows the user which item they selected before, and the onClick function is also not working well.

CodePudding user response:

You can achieve this by using a click event on the option tag.

$('#articles').on('click', 'option', function(e) {
    //adds article to list
    console.log($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="articles">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
<option>option 4</option>
<option>option 5</option>
</select>

The event will be called every time you click an option or change an option and then you can to add it to the array as before.

CodePudding user response:

Using the select2 plugin it is possible to use:

  $('#articles').on('select2:close', function(e) {
      ...
  }

This will fire the function, even if it is selected already.

Thanks to: @Pete for the answer in the comments

CodePudding user response:

Use select2()

$('#articles').select2().on('click', function() {
    console.log('selected : ', $(this).val());
});

$('#articles').select2().on('click', function() {
  console.log('selected : ', $(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<select id="articles">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

  • Related