Get the value in an input text box using jQuery

Learn, how can we get the value of an input text box given using jQuery?
Submitted by Pratishtha Saxena, on August 23, 2022

Input box can be a text box, text area, or some other forms of input like radio buttons, and checkboxes in which the user enters the value. This value sometimes needed to be stored somewhere else, for example – in a database or for some calculations. Therefore, it gets necessary for the programmer to have an access to this value or text entered by the user and get it.

Using jQuery, we'll get this data of an input tag with the val() method. This method helps in accessing the value of the specified element. It not only gets the value but is also useful to set the value if needed.

Syntax:

$('selector').val();

This value extracted by the val() method can be stored in some new variable and then be used afterward as needed. Here, we'll be getting it on the console screen using console.log().

Example to get the value in an input text box using jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Let's get the value of the Input Box using jQuery</h2>
    <p>When the button is clicked, the values of following can be seen on console.</p>
    <label>Enter Name: </label>
    <input type="text" id="myName">
    <br><br>
    <label>Enter Age:</label>
    <input type="text" id="myAge">
    <br><br>
    <label>Choose Gender:</label>
    <input type="radio" value="Female">Female
    <input type="radio" value="Male">Male
    <br><br>
    <button type="button" id="button1">Get Value</button>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('#button1').on('click',function(){
            console.log(
                $('#myName').val(), 
                $('#myAge').val(), 
                $("input[type = 'radio']:checked").val());
        });
    });    
  </script>
</html>

Output:

Example: Get the value in an input text box






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.