14
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

サーバーにデータを送信できる読み取り専用フォームを作る

Posted at

動機

入力画面 → 確認画面 → 登録完了画面というような画面遷移をするWebアプリケーションを作る際に、できるだけ入力画面と確認画面を共通化したい。
さらに確認画面から登録完了画面に遷移するタイミングでデータを更新するので、入力画面からだけではなく確認画面からも入力値をサーバーに送信する必要がある。

解決策

入力画面と確認画面は同じHTMLフォームを使いつつ、確認画面ではユーザーがフォームに表示されているデータを変更できないようにする。

確認環境

Mac

  • Safari 5.1.7
  • Chrome 20.0.1132.57
  • Firefox 14.0.1

Windows

  • IE9
  • IE8
  • IE7

テキストボックス/テキストエリアの場合

readonly属性を付ける。なお、disabled属性を付けるとサーバーにデータが送信できないので、今回の動機を充たさない。

<input name="a" type="text" value="hoge" readonly="readonly" />
<textarea name="b" readonly="readonly">piyo</textarea>

テキストボックスとテキストエリア以外はreadonly属性が使えないのでJavaScript(CoffeeScript)でユーザーの操作を無効化する等の工夫が必要になる。

セレクトボックスの場合

onfocusイベントで変更前の値を保存し、onchangeイベントで強制的に変更前の値に戻す。
ここでは画面内の全セレクトボックスにそのような処理を付加するjQuery + CoffeeScriptの例を示す。

$('select').live 'focus', ->
  this.previous_value = this.value

$('select').live 'change', ->
  this.value = this.previous_value

ラジオボタンの場合

チェックされていないラジオボタンにdisabled属性を付けることで、「1つしか選択できないラジオボタン」を作る。
HTMLタグに直接disabled属性を付ける方法もあるが、ここでは画面内の全ラジオボタンに一括でdisabled属性を付与するjQuery + CoffeeScriptの例を示す。

$(':radio:not(:checked)').attr('disabled', true)

チェックボックスの場合

jQueryのpreventDefaultメソッドを使って、onclickイベントを無効化する。

$(':checkbox').live 'click', (e) ->
  e.preventDefault()

参考情報

画面のデザインについて

値の変更を抑制するだけではなく、フォームが読み取り専用になっていることがわかるように、視覚的な変化を加えることが望ましい。

参考にしたWebサイト

14
17
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
14
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?