Change value of a button with JavaScript/jQuery
This post will discuss how to change the value of the <input> element of type button or submit in JavaScript and jQuery.
1. Using jQuery
With jQuery, you can use the .val() method to set values of the form elements. To change the value of <input> elements of type button or type submit (i.e., <input type="button"> or <input type="submit">), you can do like:
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $(this).val('Processing…'); }) }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <input type="button" id="submit" value="Submit" class="btn"> </body> </html> |
CSS
|
1 2 3 4 5 |
.btn { font-size: 14px; margin: 8px; padding: 0 15px; } |
Alternatively, you can use jQuery’s .prop() method.
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $(this).prop('value', 'Processing…'); }) }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <input type="button" id="submit" value="Submit" class="btn"> </body> </html> |
CSS
|
1 2 3 4 5 |
.btn { font-size: 14px; margin: 8px; padding: 0 15px; } |
2. Using JavaScript
With JavaScript, you can modify the <input> elements’ value attribute, which contains a DOMString used as the button’s label.
JS
|
1 2 3 |
document.getElementById('submit').onclick = function() { this.value = 'Processing…'; } |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <input type="button" id="submit" value="Submit" class="btn"> </body> </html> |
CSS
|
1 2 3 4 5 |
.btn { font-size: 14px; margin: 8px; padding: 0 15px; } |
That’s all about changing the value of a button in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)