简体   繁体   中英

Rails 4: How to Disable Text Field Based on Checkbox Value Using JQuery in Rails

I have a check box and a text field in a form. If the checkbox is checked, I want to disable the field (and if it's unchecked, I want it to be enabled).

I tried to write some jQuery based on the second answer for this question: jQuery - checkbox enable/disable

However, the text field is (foo_price) is disabled when the page loads even though the field is unchecked. What am I doing wrong?

I'm using the Simple Form gem :

<%= simple_form_for @foo do |f| %>
  <%= f.input :free_flag, as: :boolean %>
  <%= f.input :price  %>

  <%= f.button :submit %>
<% end %>

The form renders:

<form>
  <input class="boolean optional" type="checkbox" value="1" name="foo[free_flag]" id="foo_free_flag" />
  <input class="numeric decimal optional" type="number" step="any" value="12.99" name="foo[price]" id="foo_price" />
</form>

My Coffeescript:

enable_cb = ->
  $('#foo_price').prop 'disabled', !@checked
  return

  $ ->
    enable_cb()
    $('#foo_free_flag').click enable_cb
    return

The problem arise from the fact when you use enable_cb() on DOM load directly the property checked its refers to window object rather than checkbox element

I would recommend the usage of change event instead of click for checking the checked property. You should use .trigger(event) to programmatically execute the event handler.

enable_cb = ->
  $('#foo_price').prop 'disabled', !@checked
  return

$ ->
    $('#foo_free_flag').change enable_cb 
    .trigger('change')
    return

You can make use of javascript/jquery to do this, check this out this fiddle

<input type = "text" class="txt1"/>
<input type="radio" class="radio1"/>

$(function(){
$(".radio1").change(function(){
alert($(".radio1").prop("checked"));
if($(".radio1").prop("checked") == true){
  $(".txt1").prop("disabled", true);
}else{
    $(".txt1").prop("disabled", false);
}
});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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