简体   繁体   中英

how to find if a value selected in multiple select2?

I have a multiple select2 dropdown as below:

    <select id="ddlServices" class="js-basic-multiple select2-hidden-accessible" multiple="" style="width: 100%" tabindex="-1" aria-hidden="true">
           <option vlaue='1'>one</option>
           <option vlaue='2'>two</option>
           <option vlaue='3'>three</option>
           <option vlaue='4'>four</option>
    </select>
<asp:HiddenField ID="hfServices" runat="server" />

I have a hidden field to save select2 selected values on the dropdown change event.
I want to show an alert if user selects option 3 in single or multi-select on the dropdown. I try this as shown below.

<script>
    $('#ddlServices').on('change', function () {
        $('#<%=hfServices.ClientID%>').val($(this).val());
        var other = $('#<%=hfServices.ClientID%>').val($(this).val());
        if (other.search('3')) {
            alert('somthing');
        }           
    });
</script>

But my code always shows an alert. how to show an alert if the user has selected value 3 in multi-selected or one selected value from the dropdown.

You have a few problems here, the first one is that you wrote "vlaue" insead of "value" on the html code.

The second problem is that you wrote "$('#<%=hfServices.ClientID%>').val" for some reason.

you can change your js to this code:

$('#ddlServices').on('change', function () {
    if ($(this).val()[0] == '3') {
        alert("somthing");
  }           
});

and html to this:

<select id="ddlServices" class="js-basic-multiple select2-hidden-accessible" multiple="" style="width: 100%" tabindex="-1" aria-hidden="true">
       <option value='1'>one</option>
       <option value='2'>two</option>
       <option value='3'>three</option>
       <option value='4'>four</option>
</select>
<asp:HiddenField ID="hfServices" runat="server" />

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