获取多个选择元素的最后选择的值 [英] Get last selected value of multiple select element

查看:54
本文介绍了获取多个选择元素的最后选择的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些选择框,已将其设置为接受多个值.无论如何,我可以使用jQuery获得最后选择的值吗?我尝试使用以下内容:

I have a number of select boxes that have been set to accept multiple values. Is there anyway that I can use jQuery to get the last selected value? I've tried using the following:

var latest_value = $("option:selected",this).val();

,它什么也没返回.我只想要最后选择的值,而不是值的数组.

and it returned nothing. I only want the last selected value and not the array of values.

提前谢谢

根据要求,这里是HTML,因为长度太长,我已将其缩减:

As requested here's the HTML I've cut the list down as it's too long:

<select id="style-list" name="style-list[]" class="attrs" multiple="multiple">
    <option value="7">2 Pack</option>
    <option value="10">3 Pack</option>
    <option value="12">4 Pack</option>
</select>

然后在页面顶部,我有以下内容(我有8个,但是我已经显示了一些,以便您可以看到我正在使用multiselect小部件的多个实例:

Then at the top of the page I have the following (I have 8 of these, but I've shown a few so that you can see that I'm using multiple instances of the multiselect widget:

$(document).ready(function(){

    $("#product-list").multiselect({
       selectedList: 4,
       noneSelectedText: "Product",
       minWidth: 190  
    }).multiselectfilter();

    $("#style-list").multiselect({
       selectedList: 4,
       noneSelectedText: "Style",
       minWidth: 190  
    }).multiselectfilter();


    $("#feature-list").multiselect({
       selectedList: 4,
       noneSelectedText: "Features",
       minWidth: 190  
    }).multiselectfilter();

});

然后将其保存在单独的js文件中:

and then I have this in a seperate js file:

$(function(){

    $(".attrs").on("multiselectclick", function(event, ui){

    var latest_value = $('option', this).filter(':selected:last').val(); 
    alert (latest_value);

    var view = $("#currentview").val();
    var page = 1;

    run_ajax(view,page);

    });

})

谢谢

推荐答案

使用 :last 选择器:

Use the :last selector:

var latest_value = $("option:selected:last",this).val();


可能是因为回调函数上下文中的this不是引用<select>元素本身,而是引用其中的元素,因此请尝试以下操作:


It may be that this in the context of the callback function doesn't refer to the <select> element itself, but instead to an element within it, so try the following:

var latest_value = 
$(this).closest('select').find('option').filter(':selected:last').val();

在回调函数中调用console.log(this);也许也是值得的,只是这样您才能知道实际使用的是什么元素.

It may also be worth calling console.log(this); inside the callback function, just so you know what element you're actually working with.

这篇关于获取多个选择元素的最后选择的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆