Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I select an element by name with jQuery?
To select an element by name with jQuery, use the name attribute selector for the input field. The syntax is $("[name='attributeName']") or $("element[name='attributeName']") to be more specific. You can try to run the following code to select element by name ?
Example
This example demonstrates how to select an input field by its name attribute and retrieve its value ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
var sname = jQuery("#form1 input[name=sub]").val();
alert(sname);
});
});
</script>
</head>
<body>
<form name="myForm" id="form1">
Subject Name: <input type="text" name="sub" value="Java"/>
<button type="button" id="button1">Get</button>
</form>
</body>
</html>
The output of the above code is ?
When you click the "Get" button, an alert box will display: Java
Alternative Selector Methods
You can also use these variations to select elements by name ?
// Select by name attribute only
$("[name='sub']").val();
// Select specific element type with name
$("input[name='sub']").val();
// Select within a specific form
$("#form1 [name='sub']").val();
Conclusion
jQuery provides flexible ways to select elements by their name attribute using the attribute selector syntax. This method is particularly useful when working with form elements that share the same name or when you need to target specific inputs by their name attribute.
