Get Value From TextBox Using jQuery .val() | Code Snippet

Get-Values-From-Textfield-Using-jQueryCode Snippet #9: The code snippet we wrote today can fetch the value from a textbox using jQuery .val() API and throw it to an alert box. We have also added another code snippet to display the textbox value on the html document.

Fetching a textbox value in JavaScript is quite simple. We generally can fetch a textbox or text-field value in JavaScript using:



We need to set either the id for the input tag as textboxID or the name attribute to be textboxName.

In jQuery, we need to use the jQuery API .val() to get the value from the input fields of the text-box. Below you can find a quick demo using the alert box version and adding it to the html document:

DEMO 1: [Write something in the text box and hit the button]

DEMO 2: [Type something and you will see it inserted in the html document]

The HTML for Demo 1:

The HTML for Demo 2:

The above two HTML codes are simple. The html for the first demo has just a input field for the textbox and a button. The second demo html has an additional span tag with an id “message” which will be used in the jQuery to add the fetched value into the html document.

jQuery Code Snippet for Demo 1:

jQuery Code Snippet for Demo 2:

The jQuery snippets are also quite simple to understand. In both the snippets, we initiate the jQuery on click of the button with the id getTextBoxValue.

In the Demo 1, we get the value from the textbox by using the .val() and the id of the input tag. The fetched value is displayed in the alert box.

In Demo 2, we get the value using the same method but the fetched value is reference to the id “message” in the html document. Where the output is inserted. If the code finds multiple divs or spans with the same id, all those places will be inserted with the fetched value.

Remember that the value can also be fetched using a class using the dot instead of hash.

Hope you liked these code snippets. We will come up with more such code snippets in the future. Stay tuned.


Vinod Suthersan is a enthusiastic web designer still learning new things on web designing. He loves designing, hunting new designs, blogging, and crazy about Internet. Know more

You may also like...