Set value of an input text box with JavaScript/jQuery
This post will discuss how to set the value of an input text box in JavaScript and jQuery.
1. Using JavaScript
With JavaScript, the idea is to access the native value property and set its value:
JS
|
1 2 3 |
document.getElementById("submit").onclick = function() { document.getElementById("name").value = "Default value"; } |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Enter a value:</label> <input type="text" id="name"> </div> <button id="submit">Set Value</button> |
Alternatively, you can use the setAttribute() method to set an attribute’s value on the input text box.
JS
|
1 2 3 |
document.getElementById("submit").onclick = function() { document.getElementById("name").setAttribute('value', 'Default value'); } |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Enter a value:</label> <input type="text" id="name"> </div> <button id="submit">Set Value</button> |
2. Using jQuery
With jQuery, you can use the .val() method to set the value of an input text box, as shown below. Note, this method does not trigger the change event, but you can manually call the change event after setting the value using the .change() or .trigger("change") method.
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $('#name').val('Default value'); }) }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Enter a value:</label> <input type="text" id="name"> </div> <button id="submit">Set Value</button> |
That’s all about setting the value of an input text box 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 :)