jQuery attrメソッドを使ってinput要素に対して複数の属性を設定する方法
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1
構文
const 変数名 = $('input’).attr({id:xx,type:"checkbox",value:’値’,checked:true});
「attr()」メソッドを使って複数の属性を設定します。
input要素に対して、「id/type/value/checked」の属性をattrメソッドを使って一度に設定します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
const result = $('input').attr({
id: 'city',
class: 'city',
type: 'checkbox',
value: 'tokyo',
checked: true
});
console.log( result[0] );
});
</script>
</head>
<body>
<input>東京
</body>
</html>
実行結果
<input id="city" class="city" type="checkbox" value="tokyo" checked="checked">