Dynamically generate an input button with JavaScript/jQuery
This post will discuss how to dynamically generate an <input type=button> in JavaScript and jQuery.
1. Using JavaScript
In plain JavaScript, you can use the document.createElement() method to create an HTML <input> elements of type button and set its required attributes. Then to append the input element to a container, you can use the Node.appendChild() method. This approach is demonstrated below:
JS
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
document.addEventListener('DOMContentLoaded', function() { var button = document.createElement('input'); button.type = 'button'; button.id = 'submit'; button.value = 'Submit'; button.className = 'btn'; button.onclick = function() { // … }; var container = document.getElementById('container'); container.appendChild(button); }, false); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> </body> </html> |
2. Using jQuery
If you work with jQuery, you can use the .append() method to append a button at the end of the specified container. Here’s a working example:
JS
|
1 2 3 4 5 6 7 8 9 10 |
$(document).ready(function() { $('#container').append( $(document.createElement('input')).prop({ type: 'button', id: 'submit', value: 'Submit', className: 'btn' }) ); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> </body> </html> |
The code can be shortened to:
JS
|
1 2 3 |
$(document).ready(function() { $('#container').append('<input type="button" id="submit" value="Submit" class="btn">'); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> </body> </html> |
Here’s alternate version using .appendTo() method:
JS
|
1 2 3 |
$(document).ready(function() { $('<input type="button" id="submit" value="Submit" class="btn">').appendTo('#container'); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> </body> </html> |
Please note that the latest <button> element is now recommended over the <input> elements of type button to create buttons.
That’s all about dynamically generate an input type=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 :)