LoginSignup
4
15

More than 3 years have passed since last update.

jQuery による入力後の自動計算(Rails/form_with)

Posted at

[jQuery]フォームないの自動計算

Ruby側のフォームサンプル

<%= form_with(model: @user) %>
  <%= f.text_field :sample1, id: "sample1" %>
  <%= f.text_field :sample2, id: "sample2" %>

  <%= f.text_field :result, id: "result" %>
<%end%>

スクリプト側イベント定義

入力したのち変化させたいフォームないid="sample"の数値を入力し終わった時に変化する
changeイベントを使用

$('#sample2').change(function() {

変数に代入

変数に.val()メソッドで代入する
のちにそれをInteger型に変更する

var s = $(#sample1).val();
var a = $(#sample2).val();
var si = parseInt(s);
var sa = parseInt(a);

計算

先ほど代入したものの変数をそのまま引き算する

var result = si - sa

計算結果をフォームに反映

計算結果の変数resultを.val()内に代入する

$('#result').val(result)

全体コード

<%= form_with(model: @user) %>
  <%= f.text_field :sample1, id: "sample1" %>
  <%= f.text_field :sample2, id: "sample2" %>

  <%= f.text_field :result, id: "result" %>
<%end%>

<script>
$('#sample2').change(function() {
  var s = $(#sample1).val();
  var a = $(#sample2).val();
  var si = parseInt(s);
  var sa = parseInt(a);

  var result = si - sa

  $('#result').val(result)
});
</script>

これでsample2のフォームに数値を入れ終わったあとに、resultフォームに計算した数値がリアルタイムで自動入力される。

4
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
15