HOWTO · jQuery
jQuery 禁用和啟用輸入
本教程演示瞭如何在 jQuery 中禁用和啟用輸入。
啟用和禁用輸入欄位是使用 jQuery 的簡單操作。本教程演示如何禁用或啟用 jQuery 中的輸入欄位。
jQuery 禁用輸入
prop() 方法可以使用 jQuery 禁用輸入。此方法的語法如下所示。
prop('disabled', true)
它有兩個引數,值 disabled,設定為 true。讓我們嘗試一個 prop() 方法的示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Disable Enable Input with jQuery</title>
<style>
label {
display: block;
margin: 10px 0;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$(".disable").click(function(){
if($(this).prop("checked") == true){
$('form input[type="text"]').prop("disabled", true);
}
});
});
</script>
</head>
<body>
<form>
<label><input type="checkbox" class="disable"> Check the box to disable the input fields below</label>
<label>Name: <input type="text" name="username"></label>
<label>ID: <input type="text" name="username"></label>
<label>Address: <input type="text" name="username"></label>
</form>
</body>
</html>
一旦我們選中該框,上面的程式碼將禁用輸入。見輸出:

jQuery 啟用輸入
同樣,prop 方法也用於啟用 jQuery 中的輸入。啟用輸入的語法將是:
prop('disabled', false)
其中引數 true 將更改為 false,讓我們嘗試一個示例來啟用輸入。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Disable Enable Input with jQuery</title>
<style>
label {
display: block;
margin: 10px 0;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$('form input[type="text"]').prop("disabled", true);
$(".disable").click(function(){
if($(this).prop("checked") == true){
$('form input[type="text"]').prop("disabled", false);
}
});
});
</script>
</head>
<body>
<form>
<label><input type="checkbox" class="disable"> Check the box to enable the input fields below</label>
<label>Name: <input type="text" name="username"></label>
<label>ID: <input type="text" name="username"></label>
<label>Address: <input type="text" name="username"></label>
</form>
</body>
</html>
上面的程式碼首先禁用所有欄位,然後通過選中該框啟用它們。見輸出:
