JavaScript - Input Field Enable And Disable

An HTML input field can be disabled and enabled based on purpose. Here I will discuss enabling and disabling the input fields using JavaScript. For example, consider one login page after entering username, password input tag need to be enabled. Until then password field needs to be in the disabled stage.

Using JavaScript keyup function while entering a value on input field, we can enable another input tag. Similarly, submit button enable and disable are also achieved.

Below code is an example script for enabling & disabling an input fields.

<script>
$('#name').keyup(function () {
    var len = $(this).val().length;	
    if (len >= 5) {
        $("#pwd").prop("disabled", false);
    }
    else{
        $("#pwd").prop("disabled", true);
    }
});
$('#pwd').keyup(function () {
    var len = $(this).val().length;
	 if (len >= 8) {
        $("#btn").prop("disabled", false);
    }
    else{
        $("#btn").prop("disabled", true);
    }	
});
</script>

While entering username if it reaches 5 or more characters, password fields will get activated. In the same way, once a password field gets to 8 characters or more submit button will enable.

In any input field using disable keyword we can disable the field at loading point.

input type="text" name="name" id="pwd" class="form-control" disabled />

Complete code

<!DOCTYPE html>  
<html>  
<head>           
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
 </head>  
   <body>  
     <div class="container" style="width:500px;">  <br><br><br>
	  <h4>Login</h4>
		<form method="post">  
			<label>Username</label>  
			 <input type="text" name="name" id="name" class="form-control" /><br />  
			<label>password</label>   
			<input type="text" name="name" id="pwd" class="form-control" disabled /><br />  
			<input type="button" id="btn" value="Submit" disabled />
		</form>
	   </div>
	  </body>
	 </html>					 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>

$('#name').keyup(function () {
    var len = $(this).val().length;
	
    if (len >= 5) {
        $("#pwd").prop("disabled", false);
    }
    else{
        $("#pwd").prop("disabled", true);
    }
});
$('#pwd').keyup(function () {
    var len = $(this).val().length;
	 if (len >= 8) {
        $("#btn").prop("disabled", false);
    }
    else{
        $("#btn").prop("disabled", true);
    }	
});
</script>

Output

After entering an input Output page