Rails4形成动态只读字段

时间:2016-06-01 11:42:17

标签: javascript ruby-on-rails ruby

我有一个rails表单,根据用户点击的复选框,在字段上只需要读取或不读取。到目前为止我已经

<%= 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>

为什么这样做是否干净简洁?我之前从未使用过JavaScript操作ruby行,但我想在以下之间切换该numbe字段:readonly =&gt; true和:readonly =&gt;假的。

1 个答案:

答案 0 :(得分:0)

尝试:

<强> 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