Click here to Skip to main content
15,905,563 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi 
Thinking this should be so simple trying to execute a function when the selected event of JQuery select2 fires, but it doesn't fire, nothing at all in the console.

The select2 is on an aspx page on a formview, i hav removed it off the formviwew if for some reason it wasnt able to find it, exacctly the same nothing fires nothing in the console. Jquery is 3.3.1.

I am now out of ideas .....

Select2 version is 4.05, I have tried id=tagSelector" in place of name="tagSelector" I have also tried 

<pre>    <script >

        $(document).ready(function () {
            $(document).ready(function () {
                $('#tagSelector').select2();
            });
        });
    </script>


What I have tried:

<pre>HTML

Hide Copy Code
<select name="tagSelector" multiple="multiple">
<option value="Tag1">Tag1</option>
<option value="Tag2">Tag2</option>
<option value="Tag3">Tag3</option>
<option value="Tag4">Tag4</option>
<option value="Tag5">Tag5</option>
<option value="Tag6">Tag6</option>
</select>



JQuery

Hide Copy Code
<script >
$(document).ready(function() {
$('#tagSelector').select2();
});
</script>

<script>
$("#tagSeletor").on('change', function () { alert('hi'); });

// Have also tried the code below as in documentation even the on("select2:select", for V4

//$('#tagSelector').on("select2-select", function (e) {
// alert('hello');
//});
</script>
Posted
Updated 23-Oct-18 9:29am
v2

1 solution

The first thing that stands out the most to me is that you are not grabbing the element correctly. If you are going to use $('#tagSelector') then you need to add an ID="tagSelector" to your element.

<select id="tagSelector" name="tagSelector" multiple="multiple">


For more info on jQuery Selectors, please see: jQuery Selectors[^]

The second thing, because you are allowing multiple items to be selected, you could use a forEach approach like this:

$( document ).ready(function() {
    $('#tagSelector').change(function(){
        var selectedoptions = $(this).find('option:selected');
        if(selectedoptions != undefined) {
            selectedoptions.forEach(
                alert('Value: ' + $(this).val() )
            );
        }
    });
});


Hope this helps :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900