jQuery eachで複数の要素を操作するサンプル

環境
jQuery 3.6.
Google Chrome 107.0.5304.107

構文
1.inputのtypeがtextの複数要素を指定します。
$('セレクターID名’).find(“input[type=’text’]").each(function(){処理コード})

2.attrメソッドでnameとnameの値を追加します
$(this).attr(“name","属性の値");

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
//ボタン動作
$("#btns").click(function() {
/*inputのtypeがtextの要素を指定*/
$('.cft').find("input[type='text']").each(function(){
/*attrメソッドでnameとnameの値を追加する*/
$(this).attr("name","username");
})
});
});
</script>
</head>
<body>
<div class = "cft">
<input type="text" value="yamada">
<p><input type="text" value="oosaki"> </p>
</div>
<input type="button" id="btns" value="確認">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ //ボタン動作 $("#btns").click(function() { /*inputのtypeがtextの要素を指定*/ $('.cft').find("input[type='text']").each(function(){ /*attrメソッドでnameとnameの値を追加する*/ $(this).attr("name","username"); }) }); }); </script> </head> <body> <div class = "cft"> <input type="text" value="yamada"> <p><input type="text" value="oosaki"> </p> </div> <input type="button" id="btns" value="確認"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    //ボタン動作
      $("#btns").click(function() {
        /*inputのtypeがtextの要素を指定*/
        $('.cft').find("input[type='text']").each(function(){
        /*attrメソッドでnameとnameの値を追加する*/
           $(this).attr("name","username");
        })
      });
});
</script>
</head>
<body>

<div class = "cft">
      <input type="text" value="yamada"> 
      <p><input type="text" value="oosaki"> </p>
</div>
<input type="button" id="btns" value="確認">

</body>
</html>

実行結果
「確認」ボタンを押すと、テキストボックスinputの属性nameの値(username)を追加します。

jQuery

Posted by arkgame