【问题标题】:jquery select2 multiselect: How can I check if options is selected or not?jquery select2 multiselect:如何检查是否选择了选项?
【发布时间】:2017-06-11 15:33:47
【问题描述】:

我需要捕捉这两个事件:

  • 第一个选项被选中
  • 所有选项都被取消选择

Reason is - that I want to disable another dropdown (which is responsible for the content of my multiselect) when the first option is selected or all previous selected are deselected.

更新:

$('.projectSelector').on('change', function() {
        var targetProject_id = $('#project-id :selected').val();
        updateParticpantDropdown(targetProject_id);
    });

    function updateParticpantDropdown(selectedProjectId){

        $.ajax({
            type: "POST",
            url: '/xx/projects/xx/'+ selectedProjectId,
            dataType : "json",
            success: function (response, status) {
                if(status === "success") {

                    //console.log('success post');

                    if(response.result == "error") {

                        alert(response.message);

                    }else if (response.result == "success"){

                        var data = response.data;

                        $(".participantSelector").empty().select2({
                            placeholder: "Click here to select participants for above selected project",
                            allowClear: false,
                            data: data
                        });

                    }
                } else if(status === "error") {
                    // Ajax Post call failed
                    console.log('fatal ajax post call failed');
                }
            }
        });
}

这是我的 ajax 部分。当我从下拉列表中选择“.projectSelector”时,我会更新我的多选“.participantSelector”。

到目前为止工作正常!

我不想在“.participantSelector”中捕获第一个选择以禁用“.projectSelector”。反之亦然,如果在 '.participantSelector' 中未选择任何内容,则将 '.projectSelector' 设置为活动状态。

我的 html 看起来像这样:

<select name="participant_id[]" multiple="multiple" class="form-control select2me participantSelector" required="required" id="participant-id"><option value=""></option></select>

从我尝试过的文档中:

$('select').on('select2:select', function (evt) {
  // Do something
});

但这确实会触发下拉菜单中的选择 - 但不会在我的多选表单中触发。

顺便说一句,我在我的多选中选择了这个错误显示:

TypeError: b.dataAdapter 为空

【问题讨论】:

  • 你能分享一些 HTML 吗?我们会更容易以这种方式为您提供帮助

标签: jquery multi-select select2


【解决方案1】:

您可以使用first() 方法获取列表中的第一项。请参阅documentation,您可以使用:selected 选择器获取选定的选项。见documentation

尝试类似:

$('#select').on('change', function() {
    var first = $(this).find('option').first().val();
    var none = $(this).find('option:selected').length;

    if ($(this).val() == first) {
        alert('First item selected!');
    } else if (none == 0) {
        alert('All items deselected!');
    }
});

【讨论】:

  • 当所有选项都未选中时,您在哪里处理事件?
猜你喜欢
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-25
  • 2012-04-05
  • 2014-03-28
  • 1970-01-01
相关资源
最近更新 更多