jQuery prop関数を使ってテキストボックスを有効または無効にする
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1
構文
1.テキストボックスを有効にします
$(“#テキストボックスのID").prop('disabled’, false);
2.テキストボックスを無効にします。
$(“#テキストボックスのID").prop('disabled’, true);
3.ボタンの押下イベントの定義
$(“ボタンのID名").click(function(){処理コード}
prop関数を使ってテキストボックスのdisabledプロパティをtrueまたはfalseに設定します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var flg = false;
$('#show').click(function() {
if (flg) {
//無効になっている場合は、有効にします
$("#name").prop('disabled', false);
}
else { //有効になっている場合は、無効にします
$("#name").prop('disabled', true);
}
flg = !flg;
})
});
</script>
</head>
<body>
<div id="cft">
<label for="name">名前:</label>
<input type="text" id="name" name="name">
</div>
<br>
<button id="show">表示</button>
</body>
</html>
実行結果
「表示」ボタンを押すと、テキストボックスを無効にします。
再度「表示」ボタンを押すと、テキストボックスを有効にします。