「jQuery」eachで複数の要素のattr属性を追加する

環境

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Google Chrome 103.0.5060.114
Windows 10 Home 64bit
jQuery 3.6.0
Google Chrome 103.0.5060.114 Windows 10 Home 64bit jQuery 3.6.0
Google Chrome 103.0.5060.114
Windows 10 Home 64bit
jQuery 3.6.0

構文
$(要素).find(“input[type=’text’]").each(function() {処理コード}
findメソッドで子要素のinputのtypeがtextの要素を指定します。
eachメソッドで取得した複数の要素にattrメソッドでnameとdisabledの値を追加します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class = "city">
<input type="text" value="東京"><br>
<input type="text" value="大阪"><br>
<input type="text" value="福岡">
</div>
<input type="button" id="btnupdate" value="変更">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$("#btnupdate").click(function() {
$('.city').find("input[type='text']").each(function() {
$(this).attr("name","city")
$(this).attr("disabled","disabled")
})
});
</script>
</body>
</html>
<!DOCTYPE html> <html> <head> </head> <body> <div class = "city"> <input type="text" value="東京"><br> <input type="text" value="大阪"><br> <input type="text" value="福岡"> </div> <input type="button" id="btnupdate" value="変更"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $("#btnupdate").click(function() { $('.city').find("input[type='text']").each(function() { $(this).attr("name","city") $(this).attr("disabled","disabled") }) }); </script> </body> </html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class = "city">
      <input type="text" value="東京"><br>
      <input type="text" value="大阪"><br>
      <input type="text" value="福岡">
</div>

<input type="button" id="btnupdate" value="変更">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
      $("#btnupdate").click(function() {

            $('.city').find("input[type='text']").each(function() {
                  $(this).attr("name","city")
            $(this).attr("disabled","disabled")
            })
      });

</script>
</body>
</html>

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
「変更」ボタンを押下すると、テキストボックスの要素は全部「name」、[disabled]属性の値を追加します。
「変更」ボタンを押下すると、テキストボックスの要素は全部「name」、[disabled]属性の値を追加します。
「変更」ボタンを押下すると、テキストボックスの要素は全部「name」、[disabled]属性の値を追加します。

 

jQuery

Posted by arkgame