Using JS/jQuery, what is the best way to do this?
I have 5 variables:
var fruit1 = "apple";
var fruit2 = "mango";
var fruit3 = "orange";
var fruit4 = "banana";
var fruit5 = "melon";
Then I have a list element with a certain fruit which is clicked:
<li id="banana">Banana</li>
I get its ID in the script:
$("li").on("click", function() {
var selectedfruit = $(this).attr("id");
});
How do I match selectedfruit with the variable list so that it returns fruit4 with which I can do stuff with?
Secondary question, should I put my variable list in an array?
Thanks very much.
Edit: I am very sorry, but I have made a huge mistake
I need to validate the selectedfruit with the variable name, not the variable contents.
So, the markup would be like this:
<li id="fruit4">Mystery fruit</li>
Yes, this is definitely a job for an array.
Then in your click handler, you can search this array, and get its index.
UPDATE Based off of your update, I would use an object instead.
Then you can use the ID to get the value and compare.