WEB 教程
实践 示例
HTML 参考手册
CSS 参考手册
PHP 参考手册

如何使用 jQuery 禁用或启用表单元素

主题:JavaScript / jQuery上一页|下一页

答案:使用jQuery prop()方法

您可以简单地使用 jQuery prop() 方法来禁用或启用表单元素或控件,如 <input>, <select>, <textarea> 等,使用 jQuery 动态地禁用或启用。

prop() 方法需要 jQuery 1.6 及更高版本。 让我们看看这是如何工作的:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Disable or Enable an 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="submit"]').prop("disabled", true);
        $(".agree").click(function(){
            if($(this).prop("checked") == true){
                $('form input[type="submit"]').prop("disabled", false);
            }
            else if($(this).prop("checked") == false){
                $('form input[type="submit"]').prop("disabled", true);
            }
        });
    });
</script>
</head>
<body>
    <form>
        <label>Name: <input type="text" name="username"></label>
        <label>Email: <input type="email" name="email"></label>
        <label><input type="checkbox" class="agree"> I agree to terms and conditions.</label>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

FAQ 相关问题解答

以下是与此主题相关的更多常见问题解答:

Advertisements