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

To get value of an 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 greeting Hello + YourName + ‘!’. The value from text input takes using jQuery by name.

get value by name jQuery example

<!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 Reply

Your email address will not be published.