jQuery中的下拉列表产生动态字段 [英] Dropdown in Jquery producing dynamic fields
问题描述
基本上,我想根据下拉列表中的选择动态生成表单字段.我认为此代码如下.
Basically i want to generate form fields dynamically based on the selection made in dropdown. I have this below code in my view.
<%= javascript_include_tag "hive" %>
<%= simple_form_for(@obj :html => {:class => 'form-vertical'}) do |f| %>
<%= f.input :reason, :collection => ['Human', 'Event'], :input_html => { :class => 'dropdown'} %>
<div class="toggle human" style="display:none;">
<%= f.input :name %>
</div>
<div class="toggle event" style="display:none;">
<%= f.input :date %>
</div>
<%= f.button :submit %>
<% end %>
现在我在assets/javascript/hive.js中有以下代码
Now I have below code in assets/javascript/hive.js
$('.dropdown').change(function() {
// hide divs first
$('form .toggle').hide();
// get value from dropdown
var divClass = $('.dropdown').val().toLowerCase();
alert(divClass);
// show necessary div
$('.' + divClass).show();
});
一切对我来说都很好..但是不知何故,..任何帮助都被剥夺了
Everything looks fine to me ..but somehow its not working..Any help is apreciated
推荐答案
替换
<%= simple_form_for(@obj :html => {:class => 'form-vertical'}) do |f| %>
使用
<%= simple_form_for(@obj, :html => {:class => 'form-vertical'}) do |f| %>
注意@obj后的,
.这应该给您第一个错误.
Note the ,
after @obj. This should give you first error.
第二,在<% end %>
形式后加载javascript.这样做的原因是.dropdown
元素应该存在,然后对其调用任何操作.
Second, load the javascript after the form <% end %>
. The reason for doing this is that .dropdown
element should be existing before calling any action on it.
编辑
检查 JSFiddle .
另外,请确保在您生成的HTML中包含jQuery
库.
在浏览器中呈现视图后,右键单击并执行View Source
,检查是否看到带有src jQuery.js
的script
标记.
Check the JSFiddle.
Also, make sure that jQuery
library is included in your generated HTML.
When the view is rendered in browser, right click and do View Source
, check if you see a script
tag with src jQuery.js
.
这篇关于jQuery中的下拉列表产生动态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!