selected-select显示组标签和选项选择

时间:2017-08-03 17:18:19

标签: jquery html css jquery-chosen

我选择了optdorup和相同的选项,我想显示optgroup标签&选择选择中的选定选项。请检查我的代码&建议改变。     检查这个小提琴

http://jsfiddle.net/x5q95a11



$('#clearFilters').on('click', function () {
  console.log("start clear");
  $('#columnsearch_1').val('').change();      
  $('#columnsearch_2').val('').trigger("change");              
  $('#columnsearch_3 option').prop('selected', function () {
    $('#columnsearch_3').trigger("change");    
    $('#columnsearch_4 input[type=checkbox]:checked').removeAttr('checked').trigger("click");
    return this.defaultSelected;
  });
});

$(".chosen-select").chosen();

$(".chosen-select").on('change', function (event,el) {
  var selected_element = $(".chosen-select option:contains("+el.selected+")");
  
  var selected_value  = selected_element.val();
  var parent_optgroup = selected_element.closest('optgroup').attr('label');
  
  selected_element.text(parent_optgroup+' - '+selected_value).trigger("chosen:updated");
});

 




3 个答案:

答案 0 :(得分:1)

尝试插件提供的选项。 http://jsfiddle.net/kajalc/n1cnc53c/

$(".chosen-select").chosen({include_group_label_in_selected:true});

答案 1 :(得分:0)

试试这段代码:



<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
<!-- JS -->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
  <script>
  $(document).ready(function(){
    $('.chosen').chosen().change(
        function (evt) {
            var label = $(this.options[this.selectedIndex]).closest('optgroup').prop('label');
            alert(label);
    });
  });
  </script>
</head>
<body>
<select class="chosen" style="width:300px;">
    <optgroup label="fruit">
        <option value="1">apples</option>
        <option value="2">pears</option>
    </optgroup>
    <optgroup label="veg">
        <option value="3">neeps</option>
        <option value="4">tatties</option>
    </optgroup>
    <optgroup label="omnivore">
        <option value="5">bear</option>
        <option value="6">rats</option>
    </optgroup>
</select>
</body>
</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

检查这是否是您所期望的。 http://jsfiddle.net/kajalc/qnjhb2Lr/

替换

selected_element.text(parent_optgroup+' - +selected_value).trigger("chosen:updated");

 $('.chosen-single>span').text(parent_optgroup + ' - ' + selected_value).trigger("chosen:updated");