How to Add or Change the Value of an Input Text Field with jQuery

In this article, we show how to add or change the value of an input text field with jQuery.
At times, this may be needed on your website.
For example, let's take an example of a search engine such as google. Google has an autocomplete option, if the user doesn't disable it, that will complete words or phrases of search queries. Now, let's say a user clicks on one of the autocomplete words or phrases. We want the value of this search query to put in the input text field.
This could be an application for the user of adding or changing a value to an input text field.
So, with jQuery, we can do this.
As a demonstration, let's take the text field shown below.
When you click the button below the text field, the word, 'David', will appear in the text field.
You can see that when the button is clicked the word, 'David', appears in the input text field.
So how can we do this?
The first thing we'll do is look at the HTML of the input text field.
This is shown below.
So you can see there is an input text field with an id of 'firstname' and there is a button with an id of 'button1'.
So now to give this functionality, we need jQuery code.
So the jQuery code to insert the word, 'David', into the input text field
is shown below.
So when the page has loaded up and the button has been pressed, we get the input text field with an id of 'firstname' and put the value of 'David' into it.
The jQuery val() function allows us to insert values into text fields, text areas, and other HTML form elements. Outside of form elements, you would use the jQuery html() function to change the content. But with form elements, this is done with the val() function.
So we use the val() function to insert, 'David', into the input text field with an id of 'firstname'.
Again, this could be very useful such as when a user has to select an element such as from a drop-down list that will be inserted into an input text field. This occurs such as when searching with autocomplete. This could also be useful in application for a GUI calculator. When a user presses a number or operator, this number can be transferred to to the input text field. So the jQuery val() function has numerous applications when working with HTML forms.
And this is how we can add or change values of input text fields with jQuery.
Related Resources
How to Hide an HTML Element with jQuery
How to Show an HTML Element with jQuery
How to Create a Comment System in Which Only One Reply Comment Box Can Be Open At Once with jQuery
How to Upload a File with the Click of an Image with jQuery
