views:

38

answers:

2

I am trying to set a javascript variable to be one of a few options.

If one of a few specific link shas not been clicked (i.e. the first page load), then the variable should be set to 0 or 1 (the default value).

If it has been clicked, then I want it to get a number associated with that link.

So say the html looks like this:

<a href=""><img src="icon2.png" id="icon-2"></a> |
<a href=""><img src="icon3.png" id="icon-3"></a> |
<a href=""><img src="icon4.png" id="icon-4"></a> |

The jQuery variable would be something like:

var icon_num = 2; // If 'icon-2' is clicked, etc.
+3  A: 

You could do something like this:

var icon_num = 0;
$("#someContainer img").click(function() {
  icon_num = parseInt(this.id.replace("icon-",""), 10);
});

Or, give them a data attribute that includes only the ID, like this:

<img src="icon2.png" data-id="2" />

This would simplify your code a bit, down to:

var icon_num = 0;
$("#someContainer img").click(function() {
  icon_num = parseInt($(this).attr("data-id"), 10);
});
Nick Craver
@TJCrowder - oops, thanks sir :)
Nick Craver
Why is 10 the upper limit? Is that a limit for the parseInt function? Or is that just some random integer that you put there? I noticed it in another response to another question, so just wondering.
marcamillion
This works brilliantly.
marcamillion
@marcamillion - It's the radix, so that it's parsed as a base 10 number always, even if it starts with a `0`, which by default would be handled as a base 16 number, you can ready more on the option here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt
Nick Craver
Ahh Nick. That makes sense. Ok Thanks :)
marcamillion
The issue with data-id="" is that you cease being valid HTML and older browsers may have issues with that style of attribute names.
Mike Axiak
@Mike - If you can show me an example I'll concede that, but I've never seen issues with it...and they're actually part of the HTML5 spec (though don't cause issues that I've ever seen in earlier browsers).
Nick Craver
+1  A: 

example

var icon_num = null;  // empty select

$('a').bind('click', function(ev) {

   ev.stopPropagation();

   icon_num = $(this).find('>img').attr('id').split('-')[1];

   return false;

});
andres descalzo
Thanks for this effort andres. The other example fits better for what I want to do though.
marcamillion
perfect, thanks for the reply
andres descalzo