Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple names in a jQuery element selector?

Tags:

jquery

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,

like image 667
Abude Avatar asked Jun 05 '12 09:06

Abude


2 Answers

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

var body;
$(function() {
   body = $('[name=body], [name=body2], [name=body3]').val();
});
like image 87
Douglas Avatar answered Oct 07 '22 01:10

Douglas


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.
like image 38
David Thomas Avatar answered Oct 07 '22 01:10

David Thomas