从 select2 下拉列表中选择特定选项后触发操作

Trigger an action after selection of certain option from select2 dropdown

我正在使用 Select2 下拉菜单。我想在选择 Patient 选项时触发一个事件。现在,无论单击哪个选项,它都会触发一个事件。

  <div class="col-md-3">
    {!!($errors->has('name')) ? '<div class="form-group has-error">' : '<div class="form-group">'!!} 
    {{Form::label('based on', 'Based on:')}}<br>           
    {!! Form::select('type', ['' => 'Select type'] + ['0' => 'Image', '1' => 'Patient'], null, ['class' => 'form-control select2', 'id' => 'type',  'style' => 'width: 100%;']) !!}
  </div>
</div>  
<div class="col-md-3" id="timeframe-div" style="display: none;">
  {!!($errors->has('name')) ? '<div class="form-group has-error">' : '<div class="form-group">'!!} 
  {{Form::label('based on', 'Timeframe:')}}<br>           
  {!! Form::select('timeframe', ['' => 'Select type'] + ['0' => 'Daily', '1' => 'Weekly', '2' => 'Monthly'], null, ['class' => 'form-control select2', 'id' => 'timeframe',  'style' => 'width: 100%;']) !!}  
</div>
$('#type').on("select2:selecting", function(e) { 
  $("#timeframe-div").css("display", "block");
});

来自Select2 documentation

When select2:select is triggered, data from the selection can be accessed via the params.data property:

因此,使用这个:

$('#type').on("select2:select", function(e) { 
  if (e.params.data.text === 'Patient')
    $("#id").css("display", "block");
});

请注意,这是读取您提供给 Select2 的数据的 text 属性。如果需要,您可以将其更改为使用 id

试试这个:

$('#type').change(function() {
  if($('#type option:selected').text() == 'Patient') {
   $("#timeframe-div").css("display", "block");
  }
});