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!