简体   繁体   English

如何查找是否在多个select2中选择了一个值?

[英]how to find if a value selected in multiple select2?

I have a multiple select2 dropdown as below:我有一个多个 select2 下拉列表,如下所示:

    <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.我有一个隐藏字段可以在下拉更改事件中保存 select2 选定的值。
I want to show an alert if user selects option 3 in single or multi-select on the dropdown.如果用户在下拉列表的单选或多选中选择选项 3,我想显示警报。 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.如果用户在多选中选择了值3或从下拉列表中选择了一个值,如何显示警报。

You have a few problems here, the first one is that you wrote "vlaue" insead of "value" on the html code.你有几个问题,第一个是你在 html 代码上写了“vlaue”而不是“value”。

The second problem is that you wrote "$('#<%=hfServices.ClientID%>').val" for some reason.第二个问题是您出于某种原因编写了“$('#<%=hfServices.ClientID%>').val”。

you can change your js to this code:您可以将您的 js 更改为以下代码:

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

and html to this:和 html 到这个:

<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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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