How to get multiple names in a jQuery element selector?
Why not cover all eventualities, using the attribute-starts-with selector (attribute^="value"
):
var first;
$(document).ready(function() {
first = $('[name^="body"]').val();
});
Bear in mind that this will search all elements for that particular attribute/value; so it's better to restrict the amount of work the browser has to do, for example by identifying a particular element-type:
first = $('input[name^="body"]');
Also, as the selector returns an array the val()
will be taken from the first matching element returned by the selector, it won't return an array of the values from all the matched elements.
References:
- attribute-starts-with (
attribute^="value"
)selector.
You can list multiple items in the selector, like this:
var body;
$(function() {
body = $('[name=body], [name=body2], [name=body3]').val();
});