1

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!

2 Answers 2

2

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)];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this worked well. The key was applying the field value as an object property name. Looks good.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.