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>
上面的代码首先禁用所有字段,然后通过选中该框启用它们。见输出:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。