Reputation: 677
I'm trying to use an HTML form field's value to define what variable I use in a JavaScript function. I have a solution but I think there's a more elegant way to do it.
I have two arrays of names, male and female, and my HTML form has a set of two radio buttons for male and female. On submit, I do this:
gender = $("#gender input:checked").val(); //get value of checked button
if (gender == "male" ) {
name = male[Math.floor(Math.random()*male.length)];
} else {
name = female[Math.floor(Math.random()*female.length)];
}
$("#result").html(name);
My solution is an if-else but I wondered if something can convert the gender value into a reference to the variable of the same name. Then I could replace the if-else with something like this:
name = gender[Math.floor(Math.random()*gender.length)];
I'd be curious to hear what you think. Thanks!
Upvotes: 1
Views: 263
Reputation: 134177
You could put the genders into an object:
var genderData = {
male: [ ... ]
female: [ ... ]
}
And then use the following syntax:
genderData[gender][Math.floor(Math.random() * genderData[gender].length)]
You can also simplify it a bit to make things more readable:
var gd = genderData[gender];
name = gd[Math.floor(Math.random() * gd.length)];
Upvotes: 2
Reputation: 105885
If male
/female
are global variables then they can be found in the window
object. In this case you should be able to use something like
name = window[gender][Math.floor(Math.random() * window[gender].length)];
where gender
must be a valid variable name. However, I discourage you from using global variables. Instead use a local object with the properties male
and female
.
Upvotes: 0