Hiroki
Hiroki

Reputation: 47

Calling a function based on an ID in jQuery

I have the following function:

$('#topic').change(function()

It acts on an ID that's called #topic. I would like to make this act on an ID called

#topic_1 or #topic_2 or #topic_3 etc. 

Is there a simple way to do this with jQuery using wildcards? Also how can I extract the number 1,2 or 3 and find out the value of another element labeled key_1, key_2 or key_3. I hope this makes sense to you.

Sorry it's a basic question but I am totally new to jQuery

Upvotes: 1

Views: 6772

Answers (5)

T.J. Crowder
T.J. Crowder

Reputation: 1074355

You can use id if you like (more options below), using the "attribute starts with" selector:

$('[id^="topic"]').change(function() { ... });

That selector will match any id value that starts with "topic". Be sure to put the argument ("topic") in quotes, it's (now) required.

If you have a short list of these, you may choose to simply list them directly:

$('#topic1, #topic2, #topic3').change(function() { ... });

Or you might choose some other characteristic they have in common. Popular choices:

  • Their class, using the class selector:

    $('.theClass').change(...);
    
  • Their location in the DOM. For instance, if you want to watch the change event on all fields in a form, you can start with the form and use a descendant selector, perhaps with a qualifier like :input (which matches input, select, and textarea elements), like this:

    $('#formId :input').change(...);
    
  • Some other attribute they share, using an "attribute equals" selector, "attribute contains" selector, etc.

As you can see, you have a lot to choose from, far more than just IDs and classes. Note that on most browsers, class selectors will be the fastest, but this only really matters on very complex pages or when you're looking up selectors a lot. Optimize if/when you see a problem, as always.

Upvotes: 6

Khalid Amin
Khalid Amin

Reputation: 902

Using a class selector is preffered way to do it. However, for arbitrary names you can also implement something similar to this:

for (i=0;i<blahblah;i++){
$("#topic_"+i).change(function() {}); }

Upvotes: 0

Harish
Harish

Reputation: 2324

Like this

$('input[id^="topic"]').val('news here!');

$(input[id^="topic"]).change(function(){

  //Do something

 });

Upvotes: 1

Vivek
Vivek

Reputation: 11028

use class attribute..

$('.topic').change(function() { });

Upvotes: 0

FarligOpptreden
FarligOpptreden

Reputation: 5043

Why not use a class selector instead? Gives all the elements a CSS class called "topic" and modify your code as follows:

$('.topic').change(function() { });

Upvotes: 1

Related Questions