首页 > 解决方案 > 在多选中获取当前选项

问题描述

如何在 Jquery 中获取当前选中/未选中multiselect

我已经知道如何在multiselect. 问题是我需要获取用户单击时当前已选择/未选择的那个。这看起来像一个微不足道的问题,但到目前为止我还没有真正找到合适的解决方案。

这是我之前尝试过的:

$('#mySelect').change(function(){
   var element = $(this).val();
})

不幸的是,它返回一个包含所有选定选项的数组。我需要的是获取用户当前选择或未选择的值。我只是尝试使用辅助变量自己创建一个方法,现在看来它可以工作了。

    if($(this).attr('id').includes('Type')) Key = "trackertype";

    if(selectedValue.length > 0 && $(this).val() == null){
        Value = selectedValue[0].toString();
        selectedValue = [];
        Key = '-' + Key;
    }else if(selectedValue.length == 0 && $(this).val() != null){
        selectedValue.push($(this).val()[0]);
        Value = selectedValue[0].toString();
    }else if(selectedValue.length > 0 && $(this).val() != null && selectedValue.length < $(this).val().length){
        var selected = true;
        $.each($(this).val(),function(i,item){
            var current = item.toString();
            $.each(selectedValue,function(i,itemV){
                if(current != itemV.toString()){
                    Value = current.toString();  
                    selectedValue.push(current.toString());  
                    selected = false;                                   
                }
            });
        });
    }else if(selectedValue.length > $(this).val().length){
        $.each($(this).val(),function(i,item){
            var current = item.toString();
            $.each(selectedValue,function(i,itemV){
                if(current != itemV.toString()){
                    Value = itemV.toString();  
                    selectedValue = jQuery.grep(selectedValue, function(value) {
                        return value != itemV.toString();
                    });
                    selected = true;                                   
                }
            });
        });
    }
    if(selected){
        Key = '-' + Key;
    }

我需要将值(当前选定选项的值)和键(选择名称)发送到 Web 服务。它不是最好的代码(对此感到抱歉),但它确实完成了它的工作。

谢谢

标签: javascriptjquery

解决方案


var selectedItems =  document.querySelectorAll('#selectBoxid option:checked');
// here selectboxid is id of select element of your page.

当任何 html 元素都可以使用时,这很简单document.getElementsById('id')

就像您想使用 css 类或任何 css 选择器而不是元素的 id 或 html 元素的名称来获取 html 元素一样。

例如 :

<p class="text-center" > abcd </p> 

然后,我们可以使用以下方法检索所有 html:

document.querySelectorAll('.text-center')

在给定的示例中,我们想要为我使用的属性选择的选项 html 元素:

document.querySelectorAll('option:checked'); 

推荐阅读