LoginSignup
7
1

More than 3 years have passed since last update.

$('input[value="aaa"]') は「"aaa"と入力されたinput要素」ではない

Last updated at Posted at 2020-08-10

かなり驚いたので初めて記事を書きます。

だめな例

"aaa"と入力されたinput要素のvalue属性を表示するプログラムのつもり。(つまり"aaa"が返ってくるはず)

HTML
<input type="text" name="phrase">
JavaScript
const check = () =>{
   const target = $('input[value="aaa"]');
   console.log(target.val());
}

image.png
"aaa"と入力して、consoleでcheck();を呼び出すと当然"aaa"...ではなくundefined

原因

どうやらこちらによると、

If you are changing value dynamically it wouldn't get selected by attribute selector.

この属性セレクタはユーザーによって動的に変更された値に対しては使えないそうです。1

Attribute selector will not check the dom node's value property it only targets the element's attribute

この属性セレクタは、その要素の属性のみを対象とし、ノードのvalueプロパティはチェックされません。1

解決策

filterを使いましょう。2

HTML
<input type="text" name="phrase">
JavaScript
const check = () =>{
   const target = $('input').filter(function() {
       return this.value == "aaa"
   });
   console.log(target.val());
}

image.png
"aaa"と入力して、consoleでcheck();を呼び出すと..."aaa"!!

参考

javascript - Why Jquery selector by 'value' not work in case of dynamic change - Stack Overflow


  1. もちろん、元からinputvalue="aaa"と指定されているものをセレクタで見つける際には使えます。また、ブラウザのデバッグツールを使って後から属性を追加した場合も同様。ポイントは動的かどうかというより属性として与えられているかどうかみたいですね。 

  2. ここでアロー関数で書こうとするとコケます。詳しくは"js アロー関数 this"。  

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