0

I have form elements like this:

<input type='text' id='person_1_name'>
<input type='text' id='person_2_name'>
<input type='text' id='person_3_name'>
<input type='text' id='person_4_name'>
<input type='text' id='person_5_name'>
..
..
..

I can select single element like this:

$("#person_1_name").focusout( function() {

   alert("Hello World");

});

Is there any selector that select all elements(person_<*>_name) like this without describing them separately ?

Thanks

1
  • Woudn't it be simpler to wrap them in an element and then acces them like this: $('wrapperelement input').focosout(function() { /**/ }); ? Commented Sep 19, 2011 at 13:43

7 Answers 7

3

this is not the right way .

you should add Class to each of the elements and then select it by :

$(".MyClass")...

but if you insist :

  $('div') .filter(function() { return this.id.match(/person\_[0-9]\_name/); }) .css('border','solid 1px red')
Sign up to request clarification or add additional context in comments.

1 Comment

+1. You can use filters on the ID value, but I'd rather avoid it where possible.
3

JQuery emulated CSS selectors. So, this should work well:

$('input[id^="person_"][id$="_name"]');

Comments

2

$("id[id^='person_']"); //starts with
$("id[id$='_name']"); //ends with

Comments

1

Add a class to the person_n_name elements and use a class selector instead.

Comments

1

You could try by picking them with a class. First set them a class and then pick them via script

like this:

<input type='text' id='person_1_name' class='person'> 
<input type='text' id='person_2_name' class='person'> 
<input type='text' id='person_3_name' class='person'> 
<input type='text' id='person_4_name' class='person'> 
<input type='text' id='person_5_name' class='person'> 

<script type="text/javascript">

var person = $(".person");

person var will contain a array

Comments

1

The best way is to add class='person_name' in your input and use

$(".person_name")focusout( function() {

   alert("Hello World");

});

But if you are forced to use id then you can use the code below

$("input[id^='person_'][id$='_name']").focusout( function() {

   alert("Hello World");

});

See a working demo here http://jsfiddle.net/usmanhalalit/aPD5K/

Comments

0

This should work (untested)

$('input[id*="person"]')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.