【问题标题】:Trigger an action after selection of certain option from select2 dropdown从 select2 下拉列表中选择某个选项后触发操作
【发布时间】:2020-02-14 09:25:17
【问题描述】:

我正在使用 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");
});

【问题讨论】:

  • 在询问与服务器端逻辑不相关的问题时,为了将来参考,请将 HTML 输出发布到问题中,而不是任何创建它的模板逻辑。

标签: jquery jquery-select2


【解决方案1】:

来自Select2 documentation

select2:select 被触发时,可以通过 params.data 属性访问来自选择的数据:

因此,使用这个:

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

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多