「jQuery」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

構文

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$(要素).attr(
"value",function(){
処理コード
});
$(要素).attr( "value",function(){ 処理コード });
$(要素).attr(
      "value",function(){
       処理コード
});

attrメソッドの2つめの引数は関数を使用します。
戻り値が属性値として設定されます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
</head>
<body>
名前:<input type="text" id="txtName" value="山田" maxlength="5" disabled>
<p><input type="button" id="btnReg" value="検証" ></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$("#btnReg").click(function() {
// 属性値を設定
$("#txtName").attr(
"value",function(){
return "大崎";
});
});
</script>
</body>
</html>
<!DOCTYPE html> <html> <head> </head> <body> 名前:<input type="text" id="txtName" value="山田" maxlength="5" disabled> <p><input type="button" id="btnReg" value="検証" ></p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $("#btnReg").click(function() { // 属性値を設定 $("#txtName").attr( "value",function(){ return "大崎"; }); }); </script> </body> </html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
名前:<input type="text" id="txtName" value="山田" maxlength="5" disabled>
<p><input type="button" id="btnReg" value="検証" ></p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>
  $("#btnReg").click(function() {
    // 属性値を設定
    $("#txtName").attr(
      "value",function(){
        return "大崎";
    });
  });

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

結果
「検証」ボタンを押下すると、テキストボックスに「大崎」が表示されます。

jQuery

Posted by arkgame