Nechama Goldman
Nechama Goldman

Reputation: 45

disable input on checkbox in rails app

I have a date input dropdown on a form in my rails application.

I'd like there to be a checkbox that- when checked/selected by the user- will (#1) disable the date input and (#2) populate the date input with the current date.

I've looked at previous SO answers to get an idea of how to do this and here's what I tried to accomplish #1:

app/assets/javascripts/application.js

 //= require jquery
 //= require bootstrap
 //= require jquery_ujs
 //= require turbolinks
 //= require_tree .

$(document).on('change', '#availableNow', function(){
    debugger;
    if($(this).prop('checked')){
        $('#fromDatePicker').attr('disabled', 'disabled');
    } else {
        $('#fromDatePicker').removeAttr('disabled');
    }
});

In the form...

app/views/apartments/_form.html.erb

   <div class="field">
      <%= f.label :available_now %>
      <%= f.check_box :available_now, id:"availableNow" %>
    </div>
    <div class="field">
      <%= f.label :to_date %><br>
      <%= f.date_select :to_date, {:include_blank => true, :default => nil, :start_year => Date.today.year, :end_year => Date.today.year + 4, :order => [:month, :day, :year] }, id:"fromDatePicker" %>
    </div>

Rails generates 3 dropdown menus for the date picker (day, month & year). Only month (the first dropdown) is disabled when the box is checked.

Any ideas how to get the checkbox functionality to work for all the dropdowns?

Any idea how to "grey out" the dropdowns once they are disabled?

Thanks in advance!

Upvotes: 0

Views: 1740

Answers (1)

Ravi Mariya
Ravi Mariya

Reputation: 1230

first check the html generated from f.check_box if you can see id: 'your_id'

$('#availableNow').on('click', function(){
 if($(this).prop('checked')){
  $('#fromDatePicker').attr('disabled', 'disabled');
 } else {
  $('#fromDatePicker').removeAttr('disabled');
 }
})

for disable month and year, check select_id which is generated and disable them

Upvotes: 1

Related Questions