Megan Woodruff Megan Woodruff - 2 years ago 112
Ruby Question

Rails4 form dynamic read only field

I have a rails form that needs at field to be readonly or not depending on the checkbox the user clicks. So far I have

<%= form_for @weight, remote: true do |f| %>
<div class= "modal-body">
<input id="checkbox1" type="checkbox" onclick="ReadOnly()"></input>
<%= f.label :weight_number, class="control-label"%>
<%= f.number_field :weight_number, :readonly => true, class="form-control"%>
<% end %>
function ReadOnly(){
//make the number field editable

Is there a clean and concise why do this. I've never had to manipulate a ruby line via JavaScript before, but I would like to toggle that numbe field between :readonly => true and :readonly => false.

Answer Source



<input type="checkbox" name="suspended" id="checkbox1" value="test"/>
<input type="number" name="weight_number" id="weight_number_id">


$(document).ready(function() {
  $("#checkbox1").change(function() {
    if (!this.checked) {
      $("#weight_number_id").attr('readonly', 'true');
    else {
  //triger change event in case checkbox checked when user accessed page

Working Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download