If Else 在 HAML 中检查 "select" 框的值

If Else in HAML to check the value of a "select" box

= form_tag questions_path, :method=>:post do
    = label :question, :type, 'Type: '
    = select :question, :type, %w(Text Picture Audio Video), :id=> :question_type_combo
      **- if :question_type_combo.selected != 'Text'**
        = label :question,:url, 'URL: '
        = text_field :question,:url, :id=> :question_url_text
      = submit_tag 'Add Question',:id=>:add_question_button

在 HAML 中可以实现这种功能吗?如果在上面的 SELECT BOX 中选择,我希望只为某些选项呈现文本字段。

- if :question_type_combo.selected != 'Text' 这在 haml 视图中是不可能的,如果你想根据选择的选项做一些事情必须用js.

或者如果您有控制器对象,您可以使用类似的代码设置 selected 选项:

= select_tag("fee_discount", options_for_select(Fee.discounts.keys.map {|k| [k.titleize, k]}, selected: "#{"rewards" if @vendor.present? && @vendor.approved?}"), include_blank: true)

或者

您可以将标签和 text_field 保留在带有 hide class 的 div 中。 然后使用 javascript 你可以隐藏取消隐藏 div.

是也不是。您可以根据绑定到表单的记录的值编写条件:

= form_for @question do |f|
   = f.label :type
   = f.select, :type, %w(Text Picture Audio Video), id: 'question_type_combo'
   - unless f.object.question_type_combo === 'Text'
      = f.label :url
      = text_field :url, id: 'question_url_text'

但这只会在用户提交表单后改变可见性,并不是很有用。

相反,您可以只使用 jQuery 为“更改”事件创建事件处理程序。

$(document).on('change','#question_type_combo', function(){
   var type = $(this).first(':selected').val();
   var $other_input = $('#other_input');
   if (type == 'Text') {
     $other_input.hide();
   } else {
     $other_input.show();
   }
});

// sets the initial state
// if you are using turbolinks
$(document).on('page:load', function(){
  $('#question_type_combo').trigger('change');
});

// if you are not using turbolinks 
$(function(){
  $('#question_type_combo').trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="field">
    <label>Type</label> 
    <select name="question[question_type_combo]" id="question_type_combo">
       <option>Text</option>
       <option>Something else</option>
    </select>
  </div>
  <div class="field" id="other_input">
    <label>URL</label> 
    <input type="text" name="question[url]">
  </div>
</form>