Here is how you can disable an input field at the click of a button:
Step 1. Get the specified botton and input elements by using selector $("#id")
Step 2. Add an onclick event listener to the button element
Step 3. Set disabled attribute to input element
Here is the HTML that will be used for the example:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>wecode101 disable input on click Jquery</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<main>
<!--Main layout-->
<div class="container">
<div class="col-9 pt-5 mx-auto">
<form>
<div class="mb-3">
<label for="name" class="form-label">name</label>
<input type="text" class="form-control" id="name"/>
</div>
<button type="submit" class="btn btn-primary" id="s-btn">Submit</button>
</form>
</div>
</div>
</main>
</body>
</html>
JS
Let's look at a couple of ways to disable an input based on the steps above:
Option 1. Set disable attribute using attr() method
$( "#s-btn" ).click(function(){
event.preventDefault(); //prevents page refresh on submit
$("#name").attr("disabled", true);
});
Option 2. Set disable attribute using prop() method
$( "#s-btn" ).click(function(){
event.preventDefault(); //prevents page refresh on submit
$("#name").prop("disabled", true);
});