How to get the value in an input text box using jQuery ?

jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element. In case of the set value, it sets the value of the attribute for all elements. This element is mostly used with HTML forms.

Syntax:

$(selector).val(function(index, currentvalue))

Example 1: This example is implemented where a text is written in the field and when the show value button is clicked a popover comes up and shows the entered text.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
  
    <script>
        $(document).ready(function () {
  
            // On button click, get value
            // of input control Show alert
            // message box
            $("#getValBtnID").click(function () {
                var inputString = $("#userInputID").val();
                alert(inputString);
            });
        });
    </script>
</head>
  
<body>
    <h3 style="color:green">
        GeeksForGeeks
    </h3>
  
    <b>JQuery val() Method</b>
      
    <br><br>
      
    <input type="text" id="userInputID">
    <br><br>
  
    <button type="button" id="getValBtnID">
        Get Value
    </button>
</body>
  
</html>

chevron_right


Output:

Example 2: This implementation shows the set value property when the button is clicked. It automatically calls and fills the text box with the predefined data mentioned in the code.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
  
    <script>
        $(document).ready(function () {
            $("#setBtnID").click(function () {
                $("input:text").val("Hello World!");
            });
        });
    </script>
</head>
  
<body>
    <h2 style="color:green">
        GeeksForGeeks
    </h2>
      
    <b>JQuery val() Method</b>
  
    <p>User Text: <input type="text"
        name="userInput">
    </p>
  
    <button id="setBtnID">
        Set the value of the 
        input field
    </button>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.