In this jQuery tutorial we will learn how to get and print attribute value of any html element.
There are large number of attributes in HTML like name, lang, title, alt etc.
In this tutorial, we will get and print the value of name attribute of input fields when the input field is focused.
Step 1: HTML
Let’s create few input fields and a region to display the value of name attribute.
1 2 3 4 | <label>Name: </label><input type="text" name="name" value=""> <label>Email: </label><input type="text" name="email" value=""> <br /><br /> <div class="focus-message"></div> |
Step 2: jQuery
jQuery attr() method is used to get the value of any HTML attribute.
Syntax
1 | $('selector').attr('attribute name'); |
Use below jQuery code to get and print the value of name attribute in a div of class name focus-message
1 2 3 4 5 6 7 8 | <script> $(document).ready(function(){ $('input[type="text"]').focus(function(){ var focus_field_name = $(this).attr("name"); $('.focus-message').fadeIn().text(focus_field_name); }) }) </script> |
Full Code
Below is full code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Get Attribute Value in jQuery</title> <script src="//code.jquery.com/jquery-3.4.1.min.js"></script> <script> $(document).ready(function(){ $('input[type="text"]').focus(function(){ var focus_field_name = $(this).attr("name"); $('.focus-message').fadeIn().text(focus_field_name); }) }) </script> <style> .focus-message { display: none; padding: 10px; background: yellow; } </style> </head> <body> <label>Name: </label><input type="text" name="name" value=""> <label>Email: </label><input type="text" name="email" value=""> <br /><br /> <div class="focus-message"></div> </body> </html> |