daremkd
daremkd

Reputation: 8424

Rails - Cannot disable a button with an option box

I have this:

<%= form_tag do %>

<%= label_tag :name, 'Name: ' %><%= text_field_tag 'name' %>
<%= submit_tag 'submit', disabled: @op %>
<%= label_tag :dis_false, "True" %>
<%= radio_button_tag :dis, :true %><br />
<%= label_tag :dis_true, "False" %>
<%= radio_button_tag :dis, :false %><br />
<% end %>

Routes are set up properly and @op = params[:dis].

Now, when I try to select "false" and click "submit", the button becomes disabled. This should only happen if the optin-box "True" is selected. So I was wondering, what's going on here? I was basically trying to make a simple app that would help me enable/disable a button via an option box.

Upvotes: 0

Views: 118

Answers (2)

sites
sites

Reputation: 21795

I think I get your answer, when you send false @op is set to "false" not false.

Try this:

@op = params[:dis] == "true"

This is:

params[:dis] # comes as a string "true" or "false", since these are values radio button returns.

params[:dis] == "true" # is true without quotes when radio button with value "true"
                       # false, without quotes, otherwise, for example when
                       # when params[:dis] is "false"

Upvotes: 1

Drew
Drew

Reputation: 2631

It seems 'dis' would be better suited as a checkbox in this case. Disable/enable can also be handled via javascript / coffeescript. Add this to your js.coffee file in app/assets:

jQuery ->
  $("#dis").change ->
    $("#submit").attr "disabled", $("#dis").is(":checked")

Or in plain jQuery:

$(function() {
  $("#dis").change(function() {
    $("#submit").attr("disabled", $("#dis").is(":checked"));
  });
});

And update your form fields:

<%= submit_tag 'submit', disabled: @op, :id => "submit" %>
<%= check_box_tag(:dis, '', false) %>

Upvotes: 0

Related Questions