I have several images with the class “red”.
When the user clicks on any of them, a form field with the Id of “red” should be incremented.
I’m trying to write this in a way that is easy to re-use.
I can’t figure out if there is a way of incrementing the form field value without using a global variable. Simply writing
$(#red).val(++);
doesn’t do anything.
If I first declare a global variable like
var redAmount;
$(#red).val(redAmount++);
it works, but I don’t like the idea of having to type the color + Amount each time I re-use this for other colors.
Which made me try to form the variable name dynamically like
var redAmount;
var currentColor = $(obj).attr("class"); //getting the class of the clicked element
$('#' + currentColor).val(currentColor+'Amount'++); //trying to form the variable name dynamically but failing
Sorry for the long explanation. What I’m trying to ask is this:
- Can I increment the form value without a global variable
- If not, how do I form the variable name dynamically based on the class of the clicked element
You can do this with the increment operator in plain-old JavaScript:
jsFiddle