Abude
Abude

Reputation: 2162

How to get multiple names in a jQuery element selector?

i want to apply my script on multiple pages so the var should read 3 names not just one; this is how it looks now:

var first;
$(document).ready(function() {
  first = $('[name=body]').val();
});

need to do an or " || " or an and " && " some how so the name could be 'body','body2' and 'body3', depends on what page is it. please help

Thanks all,

Upvotes: 16

Views: 26745

Answers (4)

Alexander Behling
Alexander Behling

Reputation: 627

David Thomas answer works. I only want to mention if you want tp get all values at once (e.g. for an ajax call) you could use the serialize function which will give you a urlencoded string which you could use in the ajax functions of jQuery or any other url-based functions (e.g. window.location.href)

all = $('input[name^="body"]').serialize;

Upvotes: 0

Basheer AL-MOMANI
Basheer AL-MOMANI

Reputation: 15327

check my snippet

$('a[name="' + href + '"]' + ', a[name="' + decodeURIComponent(href) + '"]');

and the generated selector will be like

'a[name="May%2FJune"], a[name="May/June"]"'

Upvotes: 0

Douglas
Douglas

Reputation: 37763

You can list multiple items in the selector, like this:

var body;
$(function() {
   body = $('[name=body], [name=body2], [name=body3]').val();
});

Upvotes: 28

David Thomas
David Thomas

Reputation: 253307

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:

Upvotes: 11

Related Questions