jQuery – How to Get a Value of an Element by Name?

In jQuery to get the value of an HTML element you need to use  $("input[name=myNameInput]").val()  selector where myNameInput is the name of your input. Let’s demonstrate an example. Here is a text box where you need to enter your name. By clicking on the button it will show an alert with the greeting Hello + YourName + ‘!’. The value from text input takes using jQuery by name.

get value by name jQuery example
Pic 1 – HTML form with textbox and button

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
        $(document).ready(function(){
        
            $("#myTestButton").click(function(){
            
            var value = $("input[name=yourNameTextbox]").val();
            
            alert('Hello ' + value + '!');
            });
        });
    </script>
    </head>
    <body>
        <h1>Get Value By Name - Yarkul.com</h1>
            
        <label for="testTextbox">Your Name: </label>
            
        <input name="yourNameTextbox" type="textbox" value="Yaroslav" />
            
        <button id="myTestButton" type="button">Greetings!</button>
    </body>
</html>

 

At the line 10 you can see  var value = $(“input[name=yourNameTextbox]”).val();  This is the key of this example.

Watch the video to see how it works

More related to jQuery:

  1. How to check if checkbox is checked
  2. How to Set and Get the Attribute? jQuery

Leave a Comment