显示/隐藏div on下拉菜单

时间:2012-08-06 16:44:11

标签: javascript jquery ruby-on-rails haml

我有一个使用haml

的表单中的下拉菜单的代码
= f.select :contact_type, options_for_select(['String','Email','Phone','Textarea','Boolean', 'Multi Select'],
 selected: @contact_object.contact_type), onchange: "showDiv(this, @i)"
- if @contact_object.contact_type == 'Boolean'
  %div{:id=>"options_for_boolean_#{@i}"}
    %li
      =f.label :first_boolean_option do
        Field
        %span{:class => "item-number"}
          =@i
        First opt.
      =f.text_field :first_boolean_option, :placeholder => "Enter First option:"
    %li
      =f.label :second_boolean_option do
        Field
        %span{:class => "item-number"}
          =@i
        First opt.
      =f.text_field :second_boolean_option, :placeholder => "Enter Second option:"
- if @contact_object.contact_type == 'Multi Select'    
  %div{:id=>"options_for_multiselect_#{@i}"}
    %li
      =f.label :multiselect_options do
        Field
        %span{:class => "item-number"}
          =@i
        Multiselect opt.
      =f.text_area :multiselect_options, :placeholder => "Enter all options separated with comma:"

这里@i是迭代器值。 我在这里要做的是,上面的代码是循环的。每个循环都有一个带有选定值的下拉菜单。当用户选择布尔或多选选项时,它将显示相应的div以获取更多详细信息。因此,如果用户选择第二个下拉框的布尔选项,它应该在第二个迭代层中显示布尔值div。困惑?这里是更简单的解释

drop-down-box1
  div1 for boolean
  div1 for multi select

drop-down-box2
  div2 for boolean
  div2 for multi select

drop-down-box3
  div3 for boolean
  div3 for multi select

*默认情况下隐藏所有div。如果用户选择“drop-down-box2”的“boolean”,它应显示“div2 for boolean”  怎么做?

我的jQuery代码到现在为止

:javascript
$(document).ready(function() {
  function showDiv(changing,numb) {
    var sel_val = changing.options[changing.selectedIndex].val();
    if (sel_val == 'Boolean') {
      $('#options_for_boolean_' + numb).show();
    } else if (sel_val == 'Multi Select') {
        $('#options_for_multiselect_' + numb).show();
    } else {
        $('#options_for_boolean_' + numb ).hide();
        $('#options_for_multiselect_'+ numb).hide();
    } 
  }
});

1 个答案:

答案 0 :(得分:0)

实际上问题出现在select标签的haml代码中, onchange事件未正确触发。我们可以将此问题称为“ onchange html选项未出现在浏览器中”。

以下概念对我有很大帮助。

:onchange是一个html_option。这是select的语法:

**

  

选择(对象,方法,选项,选项= {},html_options = {})

**

所以在我的情况下:

= f.select :contact_type, options_for_select(['String','Email','Phone','Textarea','Boolean', 'Multi Select'], selected: @contact_object.contact_type),{},
  :onchange => "showDiv(#{@i});"

注意那里的空哈希来表示选项。 此外,我将我的javascript代码更改为以下

:javascript
$(document).ready(function() {
  function showDiv(numb) {
    var sel_val = $('#userservicepage_contactsettings_attributes_' + numb + '_contact_type').val();
    if (sel_val == "Boolean") {
      $('#options_for_boolean_' + numb).show();
    } else if (sel_val == "Multi Select") {
      $('#options_for_multiselect_' + numb).show();
    } else {
      $('#options_for_boolean_' + numb ).hide();
      $('#options_for_multiselect_'+ numb).hide();
    }
  }
});

结果整个事物变得充满活力。