简体   繁体   English

如何使用Rails中的ruby复选框启用/禁用输入字段

[英]How to enable/disable an input field with a checkbox in ruby on rails

I have a simple form for a model called Searching . 我有一个名为Searching的模型的简单表格。 I am intending to perform a search with the values specified in this form, so I want to enable input when checkbox is checked. 我打算使用此表单中指定的值执行搜索,因此我想在选中复选框时启用输入。 My code is: app/views/searchings/index.html.erb 我的代码是: app/views/searchings/index.html.erb

<%= form_for @search do |s|%>

<div class="form-group">

  <%= check_box "enable", id:"enable", type:"checkbox" %>
  <%= s.label :type %>
  <%= s.select :type, options_for_select(type_array_search), {}, class:"form-control", id:"type_select", disabled: true %>

</div>

<script type="text/javascript">

$(function () {

  var $checkbox = $('#enable'),
      $select = $('#type_select');

  $checkbox.change(function (e) {
      $select.prop('disabled', !$checkbox.is(':checked'))
  });

});

</script>

<%= s.submit "Search", class:"btn btn-primary" %>

<% end %>

But this is not working, probably the object is not recognised by its id in the script, or the function is not right. 但这不起作用,可能是对象在脚本中的ID无法识别该对象,或者该函数不正确。

You are missing a document ready and since the question was tagged jQuery, here is a jQuery solution! 您缺少准备好的文档,并且由于该问题被标记为jQuery,因此这是jQuery解决方案!

 $(function () { var $checkbox = $('[id^="enable"]'), $select = $('#type_select'); $checkbox.change(function (e) { $select.prop('disabled', !$checkbox.is(':checked')) }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="enable" type="checkbox" /> Enable <br/> <select id="type_select" disabled="true"> <option value="">Please select...</option> <option value="1">Something 1</option> </select> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM