2

Possible Duplicate:
jquery or css selector? select all id’s that start with

This code changes #idview's src attribute on mouse-over of ids 1-3.

$("#id_1, #id_2, #id_3, #etc").mouseover(function(){
    $("#idview").attr("src","id_" + this.id.substr(3,4) + ".jpg");
});

How can I select an ID by "#id_" and then a variable integer? Say for example if there were 1000 images, where it would be impractical to write this out long hand?

It may be something like $("#id_"+*)?

Community
  • 1
  • 1

3 Answers3

5

Use an attribute starts-with selector:

$("[id^='id_']").mouseover(function () {
    //Do stuff
});

It would be a little more efficient to clarify the element type before the attribute selector, but it's not clear from your question exactly what elements you're trying to select.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • Ah brilliant, didn't think of this approach. Thanks. The element types are both images if that helps? –  Oct 10 '12 at 17:56
  • @idb - You're welcome, glad I could help. In that case, just add `img` before the attribute selector: `img[id^='id_']`. – James Allardice Oct 10 '12 at 18:02
0

Simply incorporate the variable integer into a string:

var integer = 2
    myid = "id_" + integer;

$( "#" + myid ) // Selector

Although if you don't need to target specific IDs then I would go with James' answer.

Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
0
$('[id^="id_"]').mouseover(function(){
    $('#idview').attr('src', this.id + ".jpg"));
});

Or you can add a class to the elements you want to bind and then use it as selector.

$('.myClass').mouseover(function() {
    //...
});
Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82