Megan Woodruff Megan Woodruff - 6 months ago 29
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"%>
</div>
<% end %>
<script>
function ReadOnly(){
if(document.getElementById('checkbox1').checked{
//make the number field editable
}
}
</script>


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

Try:

HTML:

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

Jquery:

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

Working Demo