JuanM.
JuanM.

Reputation: 432

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

I have a simple form for a model called 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

<%= 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.

Upvotes: 0

Views: 3125

Answers (1)

Tomanow
Tomanow

Reputation: 7357

You are missing a document ready and since the question was tagged jQuery, here is a jQuery solution!

$(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>

Upvotes: 2

Related Questions