jscodes jscodes - 1 year ago 62
jQuery Question

Call function with selected parameter without using if...else statements

This s a scenario I was given and I can't think of how to do it without using conditional statements. I'm writing it in jQuery, but plain JS is fine too.

<form>
<input type="radio" name="number" value="9" checked>9
<br>
<input type="radio" name="number" value="24">24
<br>
<input type="radio" name="number" value="57">57
<br>
<button>submit</button>
</form>


A user can make a selection which will result in a function call where the single parameter is one of: 9, 24 or 57. Based on the user input the following instructions must be performed:

If the parameter is 9 then the following methods must be performed(in order):

alert('9 way to go');
// some other code i want to happen


If the parameter is 24 then the following methods must be performed(in order):

alert('24 way to go');
// some other code i want to happen


If the parameter is 57 then the following methods must be performed(in order):

alert('57 way to go');
// some other code i want to happen


usually i'd wait for the click. upon the click, check the condition and depending which one it is, fire the correct method. i feel like this is a trick question, but i'm sure i could be 100% wrong too. Any ideas how to do this without conditionals? I was thinking maybe a closure? I'm not super familiar with them though.

Answer Source

How about reading the value of the selected radio button and use that to build the alert string?

$(function(){

   $("form").submit(function(e){
     e.preventDefault();
     var v= $("input[name='number']:checked").val();
     alert(v+' way to go');
   });

});

Here is a working sample:

I don't know what your other methods you want to execute are, but you may pass the value we read to your other methods and do whatever you want there.

 var v= $("input[name='number']:checked").val();
 YourMethodA(v);
 YourMethodB(v)

But I assume, you still need to do some if condition checking on the value to do some further actions. It could be this method or the method you are calling from that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download