Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a string against a list of stored variables

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>

like image 483
izolate Avatar asked Nov 17 '25 20:11

izolate


1 Answers

Yes, this is definitely a job for an array.

var fruits = ["apple", "mango", "orange", "banana", "melon"];

Then in your click handler, you can search this array, and get its index.

$("li").on("click", function() {
    // Note: This will return -1, if it's not in the array
    var selectedfruit = $.inArray($(this).attr("id"), fruits); // 3 (arrays are zero-indexed)
});

UPDATE Based off of your update, I would use an object instead.

var fruits = {
    fruit1: "apple",
    fruit2: "mango",
    fruit3: "orange",
    fruit4: "banana",
    fruit5: "melon"
};

Then you can use the ID to get the value and compare.

$("li").on("click", function() {
    var selectedfruit = fruits[$(this).attr("id")];  // banana
});
like image 123
Rocket Hazmat Avatar answered Nov 19 '25 09:11

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!