简体   繁体   中英

select2 alert selected option when selecting the value

In select2 how can I alert the option being selected for a multiple select?

This is my code for trigger when select2 option is being selected:

<script>
    $("#list").select2();

    $('#list').on("select2-selecting", function(e) { 
        alert(this.value);
    });     
</script>

This will only alert the already selected value. Not the option that I am selecting.

I can't also do this:

var test = $('#list').val();
alert(test);

Since it will only alert the already selected options as well.

What I want is to alert the option that is still being selected. So if you click the drop-down and select an option it will alert the value of that option.

The first option is selected by default. Sorry I forgot to mention this

Get selected value with:

$(this).find('option:selected')

Or for multiple use:

$(this).val();

Use like this:

<script>
$('#list').on("select2-selecting", function(e) {
  var val = $(this).val();
  alert(val);
});
</script>

Example:

 $("#list").select2(); $('#list').on("change", function(e) { var val = $(this).val(); alert(val); }); 
 #list { width: 200px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script> <select id="list" multiple> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> </select> 

你应该坚持你当前选择的js代码列表并在这个onSelect回调找到差异,提醒它并坚持新的选择

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM