2

I have some HTML code like this:

<input id="fieldname-1" name="field_name[value][1]" value="1" type="checkbox" />
<input id="fieldname-2" name="field_name[value][2]" value="2" type="checkbox" />
<input id="fieldname-3" name="field_name[value][3]" value="3" type="checkbox" />

I want to access this with jQuery like:

$('input[field_name]').change( function() { dosomething(); });

i can not add a class field to do this by calling $('.classname') because it is rendered by the cck module of Drupal and i don't want to add this to the theme layer.

The best thing would be to let my module add a class for every field. but a quicker solution would be to know how to access these fields by jQuery

FLY
  • 2,379
  • 5
  • 29
  • 40
  • why not accessing by id? – jAndy Oct 18 '10 at 14:42
  • Because with id you can only access one field. I want my jquery to run on multiple fields ( forgot to say that in my question ) Also when i add fields i have to rewrite the jQuery code – FLY Oct 18 '10 at 14:47

2 Answers2

3

You could use the attribute equals selector to do an exact match on the name attribute.

$('input[name="field_name[value][2]"]').change(func...

Or if you wanted all the <input> elements that start with field_name, you'd use the attribute starts with selector.

$('input[name^=field_name]').change(func...

This will select all <input> elements where the name attribute starts with field_name.

Additionally, you can use :checkbox in the selector instead of input if they're all checkboxes.

Also, you could use the same approach but with the ID attribute if you wanted.

$('input[id^=fieldname]').change(func...
user113716
  • 318,772
  • 63
  • 451
  • 440
1

It seems that you need a fuzzy selector: [name^=value] Something like this might suffice:

$('[name^=field_name]').each(function(index,element){
  $(element).change(function(){})
})
Frost.baka
  • 7,851
  • 2
  • 22
  • 18