How to disable button in javascript

This is one of the simple concept in JavaScript to enable and disable the submit button using simple JavaScript code. Here the use of  Enable and disable the submit button based on the text on input field, This is like a simple validation it will not allow the user to submit the form without entering any data. When you enter the text in the input field only the submit button will enable. By Default it was in the disable mode.  I hope this simple concept will help you. Look at the demo given below.


Code for how to disable and enable submit button using simple JavaScript:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>How to disable button in javascript</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<style>
input[type="text"] {
height: 35px;
border: 1px solid #009688;
border-radius: 5px;
padding: 1px 10px;
}

button {
height: 35px;
border-radius: 5px;
border: 1px solid #0e0d0d;
padding: 9px 22px;
}
body{
padding-top:60px;
}
.swc{
padding-top:30px;
margin-left:auto;
margin-right:auto;
width:300px;
}
</style>
</head>
<body>
<h1 style="text-align:center;">How to disable button in javascript</h1>
<div class="swc">
<input type="text" placeholder="Enter your name...">
<button>Submit</button>
<p style="text-align:center; font-weight:bold; margin-top:35px; color:#009688; "> - www.sanwebcorner.com</p>
</div>
<script type="text/javascript">//<![CDATA[
$(document).ready(function() {
$('button').attr('disabled', 'disabled');
$('input[type=text]').on('input', function() {
if ($(this).val() !== '') {
$('button').removeAttr("disabled");
} else {
$('button').attr('disabled', 'disabled');
}
});
});
//]]></script>
</body>
</html>



Post a comment

0 Comments