LoginSignup
7

More than 5 years have passed since last update.

required属性の付いたselect要素の操作で引っかかったこと

Last updated at Posted at 2014-08-21

前提条件

required属性の付いたselect要素の中に入っているoption要素に対して、別のフォーム要素の選択状況に応じて、JavaScriptからselected属性やdisabled属性の有無を操作していた。

<select required>
  <option class="default-type-1" disabled>hoge</option><!-- ← こいつらの属性をJSで弄る感じ -->
  <option class="default-type-2" selected>hage</option>
  <option class="default-type-3">fuge</option>
</select>

起こったバグ

  • option要素にselectedが付いていて
  • disabledも解除されている

にもかかわらず、マウスで再選択するまで
「required属性付きなのに、項目が何も選ばれていない」
という風にブラウザ(Firefox)から怒られてしまった。

原因

内部の処理の順番としては以下のようになっていた

  1. selectedを付ける
  2. (disabledが付いていた場合は) disabledを取る

これを逆の順序

  1. (disabledが付いていた場合は) disabledを取る
  2. selectedを付ける

に変更すると、正しい動作になった。

その他

この問題を探っている間に、JSを使ったフォームの操作について、以下のことを追加で学んだ。

.attr() よりも .prop() で操作

jQueryの .attr('disabled') とか .removeAttr('disabled') のような操作をしていたが、 .prop('disabled', true) とかやった方が良いらしい。

jQueryにおけるattrとpropの違いと使いドコロまとめ
http://qiita.com/kbyay_/items/7a7ce9547f29b34a63b1

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
7