如何从jquery中的dropdownlist获取值

时间:2014-05-07 09:55:14

标签: jquery

<optgroup label="Breeding" class="parent-option">
  <option class="child-option" value="Foal Out" disabled style="font-weight: bold; color: #555555 " selected="false">Foal Out</option>
  <option value="Breeding, Foal Out, General">&nbsp;&nbsp; General</option>
  <option value="Breeding, Foal Out, Report">&nbsp;&nbsp; Report</option>

 <option class="child-option" value="Gestation" disabled style="font-weight: bold; color: #555555 " selected="false">Gestation</option>
  <option value="Breeding, Gestation,l General">&nbsp;&nbsp; General</option>
  <option value="Breeding, Gestation, Report">&nbsp;&nbsp; Report</option>

<option  class="child-option" value="Mare" disabled style="font-weight: bold; color: #555555 " selected="false">Mare</option>
  <option value="Breeding, Mare, AI Cooled Semen">&nbsp;&nbsp; AI Cooled Semen</option>
  <option value="Breeding, Mare, AI Frozen Semen">&nbsp;&nbsp; AI Frozen Semen</option>
</optgroup>

当从下拉列表中选择任何选项时,如何获取最近的子选项类和最近的父选项类值的值。

3 个答案:

答案 0 :(得分:0)

您可以使用jquery的.prevAll()方法

$("select").change(function(){
   alert($("option:selected").prevAll(".child-option").val());
});

Demo

答案 1 :(得分:0)

我认为你在寻找的是

$('select').change(function () {
    var $opt = $('option:selected', this),
        $parent = $opt.parent(),
        $child = $opt.prevAll('.child-option').addBack().first();
    console.log($parent.attr('label'))
    console.log($child.text())
})

演示:Fiddle

答案 2 :(得分:0)

要获得与所选

最接近的.child-option
  $("option:selected").prevAll(".child-option:first");

要获得与所选

最接近的.parent-option
  $("option:selected").closest(".parent-option");