JS "increment" a filename which is an integer

willsherwood
willsherwood used Ask the Experts™
on
I want to use an image src URL as the state of a tiny state machine to cycle through 4 images, triggered by onClick.
images/1.gif
images/2.gif
images/3.gif
images/4.gif

Because i have several of these <img src="..." onClick="">  per row in a table, and many rows,
i am looking for a somewhat generic solution that can be replicated without stepping on the adjacent image selection.

And the final piece of this is, i'd like it to set an input field to the "value"  (1..4) currently displaying.

Something like...
<span onClick="chgState(this)"><img src="images/1.gif"><input type="hidden" name="A_1" > </span>
...    A_2
...
... B_1   ... B_2

function chgState(ID)
// parse filename and add 1, modulo 4  and set that as the displaying image filename
// then set the input field value to this number


p.s.  i suppose if it's easier i could use the <input> field as the state, and then splice in (concatenate) the new value into the filename syntax ("images/"+integer+".gif")

thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Expert of the Year 2008
Top Expert 2008
Commented:
Hopefully I understood what you are asking. If not, please post a url to your page, or the markup that you have.
function chgState(objElement)
{
  var img=objElement.getElementsByTagName("img")[0];
  var inp=objElement.getElementsByTagName("input")[0];
  var imgID=img.match(/(\d+)\.(gif|jpg)$/i);
 
  if(imgID)
  {
    imgID=(imgID[1]%4) + 1;
    document.getElementById(inp.name.replace(/(\d+)/g,imgID)).value=imgID;
  }
}

Open in new window

Author

Commented:
excellent;  additional clarification:  what is the  onClick call (parameter) and do i put it in the  as i had guessed?
thanks!
Expert of the Year 2008
Top Expert 2008

Commented:
>>what is the onClick call (parameter) and do i put it in the <span> as i had guessed?
The function above is meant to be used with the markup you posted:

<span onClick="chgState(this)"><img src="images/1.gif"><input type="hidden" name="A_1" > </span>
 
Where "this" is a reference to the span element. So, in:
function chgState(objElement){...}
 
objElement is the same as the span that was clicked.

Open in new window

Author

Commented:
super, thanks

p.s.  i'm getting   error when i click:

Error: img.match is not a function

  var imgID=img.match(/(\d+)\.(gif|jpg)$/i);

(i'm obviously not a JS person  :)   )

thanks for your help

Author

Commented:
I tried  var imgID=img.src.match(/(\d+)\.(gif|jpg)$/i);

with no luck,  any advice?

thanks!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial