[英]Enable input field based on another input drop down field selection
我的表格如下:
<%= form_for(@employee , html: {class: 'form-horizontal', role: 'form' }) do |f| %>
<div class="field">
<%= f.label :role,"Role", :class => 'control-label' %>
<div class="controls"></div>
<%= f.collection_select(:role_id, Role.all, :id, :role_name, prompt: "-- Select --") %>
</div>
<div class="field">
<%= f.label :is_sales_report_visible," Visible Factory Sales", :class => 'control-label' %>
<div class="controls"></div>
<%= f.check_box :is_sales_report_visible, {}, true, false %>
<div class="field"></div>
<%= f.label :is_invoice_visible," Visible Invoice Details", :class => 'control-label' %>
<div class="controls"></div>
<%= f.check_box :is_invoice_visible,input_html: { :class => 'check_box' } %>
</div>
<div class="form-actions1">
<%= f.submit :class => 'btn btn-primary btn-md' %>
<%= link_to "Cancel", employees_path(), :class => 'btn btn-danger', data: { confirm: 'Are you sure you want to cancel' } %>
</div>
<% end %>
有2个角色:我的应用程序中的admin和user,将在下拉菜单中显示。 我的要求是,复选框字段应默认为隐藏,并且当我选择角色为“用户”时,此复选框必须可见。
请帮我。
将类添加到您的复选框的主div中,方法是:
<div class="field user_checkbox_fields" style="display:none;">
将此添加到您的Java脚本文件或html文件中,它可能会起作用:
$(document).ready(function(){
$("#employee_role_id").click(function () {
if($("#employee_role_id")[0].value=="User") {
$(".user_checkbox_fields").css("display","block");
}
else {
$(".user_checkbox_fields").css("display","none");
}
});
将一个类添加到“角色”的选择框中,
<%= f.collection_select(:role_id, Role.all, :id, :role_name, prompt: "-- Select --",{:class=>'role'}) %>
在您的复选框的主div中再添加一个类,然后更改为
<div class="field user_checkbox_fields" style="display:none;">
并添加javascript代码,
$('.role').change(function() {
if($(this).val() == "user") {
$('.user_checkbox_fields').show();
}
else{
$('.user_checkbox_fields').hide();
}
});
$('.role').trigger('change');
从标记(或至少某些类名称)来看,我假设您使用引导程序,对吗? 因此,您可以利用现有的东西,例如hidden
类。 如果没有,您可以随时在CSS中定义它:
.hidden {
display: none;
}
我了解生成的选择具有id employee_role_id
,因此可以这样进行。 这是@rick解决方案的稍作调整的版本。
将选择器添加到复选框包装div。 用来标识包装程序的checkboxes
,最初hidden
就是隐藏它。
<div class="field checkboxes hidden">
// your checkboxes here...
</div>
然后是一些脚本:
$(document).on("change", "select[id$='role_id']", function() {
# toggleClass applies or removes a class from DOM element
# depending on boolean value of the second argument
$(".checkboxes").toggleClass("hidden", $(this).val() != "user")
});
$("select[id$='role_id']").trigger("change");
我发现最好使用类来指示是否隐藏了某些东西。 例如,自动化测试更容易执行。
但是,如果您想避免使用此额外的hidden
类,则可以当然使用display: none;
直接在标记中,例如@rick发布。 脚本如下所示:
$(document).on("change", "select[id$='role_id']", function() {
# toggle shows or hides DOM element
# depending on boolean value of the second argument
$(".checkboxes").toggle($(this).val() != "user")
});
$("select[id$='role_id']").trigger("change");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.