Snippets

Enable or Disable Form Element using jQuery

Posted by I. B. Gd Pramana A. Putra, 07 Aug 22, last updated 07 Aug 22

Pernahkah kamu ingin mengaktifkan suatu elemen form dengan jQuery untuk input, textarea, select atapun elemen lainnya?

Have you ever wanted to enable or disable a form element using jQuery? For element such as input, textarea, select, etc..

To accomplish that you can use prop() method from jQuery to enable or disable a form element. Here's the example:

<!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>

I love sharing code snippets as most of the time, a quick code example is what we're looking for instead of long-written articles. If you think my code snippets are helpful and save you a lot of time, please consider buying me a cup of coffee :)

Support me via · paypal · buymeacoffee · ko-fi · trakteer
Contributed Snippets
Answer & Responses
    No comments yet

Wanna write a response?

You have to login before write a comment to this post.