在多选中,我需要能够获取当前所选选项的值 [英] Within a multi select, I need to be able to get the value of the currently selected option

查看:106
本文介绍了在多选中,我需要能够获取当前所选选项的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我已经将你们与我的需求混淆了.如果选择val1,则需要返回val1的函数.如果然后选择val2,但仍然选择val1作为多选的一部分,则需要返回val2.然后,我可以使用这些值来设置错误创建的输入的ID和名称.

I think I have confused you guys with what I need. If I select val1 I need the function to return val1. If I then select val2, with val1 still selected as part of the multi select, I need to return val2. Then I can use the values to set the id and name of rewly created inputs.

我有一个选择列表,其中有多个="multiple"

I have a select list that has multiple="multiple"

我想创建一个与每个选定选项关联的文本输入,并根据每个新选定选项的值设置新输入的ID和名称,但是我总是从onchange事件中获取第一项的值.不是第一个值,而是第一个选定的值.因此,如果我先选择val2,则会返回该值,但是如果我先选择val1,则val2的ID和名称将与选择val1时的ID和名称相同.

I want to create a text input associated with each selected option and set the id and name of the new input based on the value of each newly selected option, but I always get the value of the first item from the onchange event. Not the first value, but the first selected value. So if I choose val2 first, that is returned, but if I choose val1 first then val2 the id and name will be the same as when val1 is selected.

 <select id="multiSelect" multiple="multiple">
  <option value="val1">Value 1</option>      
  <option value="val2">Value 2</option>
  <option value="val3">Value 3</option>
 </select>

我使用了以下函数,它返回第一个值.

I have used the following function and it returns the first value.

 $("#multiSelect").on('change', function(evt, params) {
   alert($("option:selected", this).val());

 });

这将返回第一个选定的选项.如果再选择第二个选项,则仍会得到第一个值.我需要获取已选择的任何一个选项的值.

This will return the first selected option. If I then choose the second option, I still get the first value. I need to get the value of whichever option has been selected.

谢谢.

推荐答案

解决方法是保存以前选择的元素,并将它们与新选择的元素进行比较:

The workaround is to save previously selected elements and compare them with newly selected ones:

小提琴.

var selected = [];

$("#multiSelect").on('change', function()
{
    var value = $(this).val();
    if (!value)
    {
        selected = [];
        alert("No value is clicked");
        return;
    }
    var newSelected = value;
    var changedOnes = [];
    var direction = (newSelected.length < selected.length);
    for (var i = 0; i < newSelected.length; i++)
    {
        var isNew = true;
        for (var j = 0; j < selected.length; j++)
        {
            if (newSelected[i] == selected[j])
            {
                isNew = false;
                break;
            }
        }
        if (isNew || direction)
        {
            changedOnes.push(newSelected[i]);
        }
    }
    selected = newSelected;
    alert(changedOnes);
});

这篇关于在多选中,我需要能够获取当前所选选项的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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