문제

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/. 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". 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. 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).

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")

Fiddle

Use is method to know that selected option is last or not:

alert($(element).filter(":selected").is(:last).parent("optgroup").attr("label")); 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top