目次
Contents
“disabled”属性を制御したい
textareaとbuttonを関係づけるような実装でハマった話です。
- やりたいこと
- textareaに何か入力されたらbuttonを有効にする
- textareaが空ならbuttonを無効にする(=disabled属性を付加する)
- ぼくがかんがえたさいきょうのソースコード
<textarea name="hoge" id="hoge" cols="30" rows="10"></textarea> <!-- 最初はdisabledにしとくで --> <button type="submit" id="huga" disabled>ボタンやで</button> <script> $(function() {$("#hoge").on('input', function(event) { // 入力されてるかどうかで属性を制御したるねん if ($(this).val() === "") { $("#huga").attr('disabled') } else { $("#huga").removeAttr('disabled') }}) }) </script>
- 結果



2種類の挙動をみせる.attr()
よくよく調べてみると、attr()には引数の数によって、2種類の挙動があるようでした。
①.attr(attributeName, value) :属性の追加
Set one or more attributes for the set of matched elements.
引数を2つとると、指定した要素に1つ以上の属性をセットします。imgのsrgなんかを追加するときに便利そうです。
<img id="image"><script>$(function(){ $("#image").attr("src", "http://dummyurl.com/img/hoge.jpg");});
②.attr(attributeName) :属性値の取得
Get the value of an attribute for the first element in the set of matched elements.(jQuery API Documentation)
引数が1つのとき、attrは与えた属性の値を取ってきます。
<img id="image" src="http://dummyurl.com/img/hoge.jpg"><script>$(function(){ let url = $("#image").attr("src"); // url の値は "http://dummyurl.com/img/hoge.jpg"});
要するに、さっきの「さいきょうのソースコード」では、removeAttr()で属性を取り除くことはできたが、属性値を取得する方のattr()を使っているのでdisabledをセットできていないということだったんですね。
論理値にはprops()を
ということで結論を。
disabled
のような、trueかfalseのどちらかをとるようなものを論理値といいますが、その制御にはprop()が使えます。
<textarea name="hoge" id="hoge" cols="10" rows="3"></textarea> <button type="submit" id="huga" disabled>ボタンやで</button> <script> $(function() {$("#hoge").on('input', function(event) { if ($(this).val() === "") { $("#huga").prop('disabled', true) } else { $("#huga").prop('disabled', false) }}) }) </script>
正確には「属性」をとれるのがattr()、「プロパティ」を操作できるのがprop()ということだそうです。あ、propって”property”の略か!
(→.attr()と.prop()の違いは?)
はー、勉強になった。メモメモ。