To select elements by their name attribute using jQuery, you can use the attribute selector syntax. Here’s how:
Basic Syntax
// Select all elements with name="yourName"
$('[name="yourName"]');
Examples
- Select all elements with a specific name:
// Example HTML: <input type="text" name="username">
const usernameInputs = $('[name="username"]');
- Combine with element type for specificity:
// Select only <input> elements with name="email"
const emailInputs = $('input[name="email"]');
- Select radio buttons by name:
// Example HTML: <input type="radio" name="gender" value="male"> ...
const genderRadios = $('input[type="radio"][name="gender"]');
Key Notes
- Returns a jQuery object: You can chain methods like
.val(),.css(), or.hide(). - Multiple matches: If multiple elements share the same
name, all will be selected. - Performance: Use specificity (e.g.,
input[name="..."]) for better performance over generic[name="..."].
Alternative: Vanilla JS Equivalent
If you need plain JavaScript:
// Returns a NodeList of elements with name="yourName"
document.querySelectorAll('[name="yourName"]');
Example Workflow
<input type="text" name="city" value="New York">
<input type="checkbox" name="subscribe" checked>
// Get the value of the city input
const city = $('[name="city"]').val(); // "New York"
// Check if the subscribe checkbox is checked
const isSubscribed = $('[name="subscribe"]').prop('checked'); // true
Use the attribute selector to efficiently target elements by name in jQuery!