This write-up helps you to change the text of the button as well as disable/enable the button using Javascript. Sometimes we need this in our application while submitting the Data and prevent the user to click it again until data gets saved or click event action completes the processes.
Below is the code for submit button.
<button type="button" id="submitBtn" class="btn btn-primary" onclick="submitStudent()">Submit</button>
Inside the button click function, we can write the below code to achieve the above-desired task.
$("#submitBtn").text('Processing...');
$("#submitBtn").attr('disabled', true);
Complete javascript code for the button click event:
<script type="text/javascript">
function submitStudent() {
var data = {
Name: $("#name").val(),
Email: $("#email").val(),
Phone: $("#phone").val()
}
$("#submitBtn").text('Processing...');
$("#submitBtn").attr('disabled', true);
console.log(data);
$.ajax({
type: 'POST',
url: '/Home/AddStudent',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (response) {
console.log(response);
$("#submitBtn").text('Submit');
$("#submitBtn").attr('disabled', false);
},
error: function () {
console.log('Failed ');
$("#submitBtn").text('Submit');
$("#submitBtn").attr('disabled', false);
}
});
}
</script>
In this way, we have learned to change text of button, disable and enable the button using JavaScript.