views:

82

answers:

2

I'd ideally like to create a streamlined interface which requires the user to select one of three radio buttons such as shown here:

<form id="icon-type">
    <input type="radio" name="icon" value="apples" /> Apples
    <input type="radio" name="icon" value="oranges" /> Oranges
    <input type="radio" name="icon" value="graphes" /> Grapes
</form>

Using jQuery it's easy to determine which of the three have been selected:

var iconType = $('input[name=icon]:checked').val();

However, I need to convert the string assigned to iconType to an previously created object of the same name. I've read that eval() is the best way to do this, but have also encountered numerous warnings stating that eval() should never be used. However there seems to be no other way to perform this conversion. Thus my question: while I recognize that eval() can certainly be misused, is this a case where eval() is indeed the appropriate approach?

Thoughts much appreciated!

EDIT: @DVK, thanks! Still a bit lost though; suppose my objects look like this:

var apple = new GIcon(baseIcon);
apple.image = "http://localhost/images/apple.png";

var orange = new GIcon(baseIcon);
orange.image = "http://localhost/images/orange.png";

So I need to convert the value retrieved from the selected radio button into the appropriate object reference. How would I store these in a hash as you explain? Thanks!

+1  A: 
var obj = window[iconType]

You can also link the object directly to the input.

$(function() {
    var form = $("#icon-type");
    form.get(0).iconTypeObject = new Apples();
    form.get(1).iconTypeObject = new Oranges();
    form.get(2).iconTypeObject = new Grapes();
});

var iconObject = $('input[name=icon]:checked')[0].iconTypeObject;
ChaosPandion
@Chaos - I thought OP said "previously created", not "new" object?
DVK
@DVK - Well I assume the objects were created in the jQuery ready function.
ChaosPandion
+3  A: 

For simple strings like this, you can also simply store the matching objects in a hash, and access like this

var obj = object_map[iconType];

DVK
Thanks much for the response, I'm still a bit lost though. I've edited my original post in order to add a bit of code.
Jason
Disregard my post edit, I got it to work, thanks a million!!!!! -Jason
Jason
And the beauty of using a hash, is that you can populate it in a loop based on your sample code: `object_map[type] = new GIcon(baseIcon);object_map[type].image = image_base_url+type+".png";`
DVK