简体   繁体   English

在选择输入中获取多个子元素具有相同值的父元素

[英]Get parent element where multiple child elements have same value in select input

I have a multiselect list where values are grouped together by categories 我有一个多选列表,其中值按类别分组在一起

    <select class="multiselect" multiple="multiple">
        <optgroup label="IsStudent">
            <option value="y">Yes</option>
            <option value="n">No</option>
        </optgroup>
        <optgroup label="IsOffer">
            <option value="y">Yes</option>
            <option value="n">No</option>
        </optgroup>
    </select>

I am using http://davidstutz.github.io/bootstrap-multiselect/ . 我正在使用http://davidstutz.github.io/bootstrap-multiselect/ I am attempting to find the parent of the option element that I select. 我试图找到我选择的选项元素的父项。 I do this by: 我这样做是:

  onChange: function (element, checked) {
            if (checked == true) {
              alert($(element).filter(":selected").parent("optgroup").attr("label"));               
            }
        }

When any of my options are selected, it alerts "IsStudent" even if I select the option under "IsOffer". 选择我的任何选项后,即使我在“ IsOffer”下选择了该选项,它也会警告“ IsStudent”。 if I change the values to be unique, the alert alerts the correct parent. 如果我将值更改为唯一值,则警报将警告正确的父级。

Is it possible to detect the selected element regardless of whether my values are duplicate. 无论我的值是否重复,是否都可以检测到选定的元素。 I was hoping that it saw it as unique when the parent optgroup is different. 我希望当父optgroup不同时它将其视为唯一。 I have tried 我努力了

alert($(element).filter(":selected:last").parent("optgroup").attr("label")); 

try 尝试

$("select").find("option:selected").last().closest("optgroup").attr("label")

test on this fiddle . 这个小提琴上测试。

if you want to accept this solution, consider to accept sudhar's solution instead, as he was the first to psot the main issue (he should add the last() method call, of course). 如果要接受此解决方案,请考虑接受sudhar的解决方案,因为他是第一个发现主要问题的人(当然,他应该添加last()方法调用)。

edit : the op actually wanted the most recently selected item reported. 编辑 :操作员实际上想要报告最近选择的项目。 this one does the trick: 这一个窍门:

$("select").click( function(eve) {
    alert($(eve.target).closest("optgroup").attr("label"));
});

test on this fiddle 这个小提琴上测试

$("select").find("option:selected").closest("optgroup").attr("label")

小提琴

使用is方法可以知道所选选项是最后一个还是不是最后一个:

alert($(element).filter(":selected").is(:last).parent("optgroup").attr("label")); 

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

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