[jQuery]filterメソッドで要素を絞り込んで処理を行うサンプル
環境
jQuery 3.6.0
Google Chrome 105.0.5195.127
Windows 10 home
構文
$(セレクタ名).filter(function() {
処理コード
});
filterメソッドを使って、要素を絞り込んで処理を行います。
書式
return $(this).val() > 変数名;
各要素について、関数がtrueを返す場合、その要素は対象として残ります。
関数がfalseを返す場合、その要素は除外されます。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function () {
$("#btnchk").click(function(){
const nn = 35;
// filterメソッド
$(".age").filter(function() {
// 関数で要素をフィルタリングする
return $(this).val() > nn;
}).css("background","red");
});
});
</script>
</head>
<body>
<p><input type="text" class="age" value="33" maxlength="2"></p>
<p><input type="text" class="age" value="44" maxlength="2"></p>
<br>
<input type="button" id="btnchk" value="検証" />
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function () {
$("#btnchk").click(function(){
const nn = 35;
// filterメソッド
$(".age").filter(function() {
// 関数で要素をフィルタリングする
return $(this).val() > nn;
}).css("background","red");
});
});
</script>
</head>
<body>
<p><input type="text" class="age" value="33" maxlength="2"></p>
<p><input type="text" class="age" value="44" maxlength="2"></p>
<br>
<input type="button" id="btnchk" value="検証" />
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function () { $("#btnchk").click(function(){ const nn = 35; // filterメソッド $(".age").filter(function() { // 関数で要素をフィルタリングする return $(this).val() > nn; }).css("background","red"); }); }); </script> </head> <body> <p><input type="text" class="age" value="33" maxlength="2"></p> <p><input type="text" class="age" value="44" maxlength="2"></p> <br> <input type="button" id="btnchk" value="検証" /> </body> </html>
実行結果
「検証」ボタンを押すと35より大きい値のテキストボックスの色が変わります。