Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing a massive IF statement in jQuery

I have an if statement that has over 100 different if's.

at the minute im using something similar to this...

$('select').on("change",function(){
    if(  $(this).val() === 'tennis' )  {
        $('.sport').val('raquet');
    }
    else if(  $(this).val() === 'soccer' )  {
        $('.sport').val('goal');
    }
    if(  $(this).val() === 'snooker' )  {
        $('.sport').val('cue');
    }
});

I want to build one for counties in the uk, so if a user selects 'london' in the dropdown, the next field is populated with the postcode for london.

My problem is however, I could build it as my above example, only it would be huge.

Is it possible to have some sort of xml file to do this? or would it be possible to put each county and its value into an object inside an array and target it this way?

Any help is greatly appreciated, thanks

http://jsfiddle.net/4xQeX/

like image 935
Liam Avatar asked Aug 14 '13 12:08

Liam


People also ask

Can you use if statement in jQuery?

The conditional loops that can be worked in a jQuery script are 'if' statement, 'if..else' statement, and 'if..else if' statement.

What does $$ mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.

Which loop is faster in jQuery?

In case of multiple iterations of the loop, and where the size of array is too large, for loop is the preference as the fastest method of elements' iteration.

How do I know which tab is clicked in jQuery?

var selectedTab = $("#TabList"). tabs(). data("selected. tabs");


1 Answers

The usual solution is to store your sport/object pairs as data, because it is data.

var tbl = {
    tennis: 'raquet',
    snooker: 'cue',
    ...
};

and then use this simple code :

$('select').on("change", function(){
    var t = tbl[$(this).val()];
    if (typeof t === "string") $('.sport').val(t);
});

You even could fetch tbl from a separate JSON file (or simply store it in another JS file) for easier management.

Supposing you want to use a separate JSON file, called things.json, then your file would be like this :

{
    "tennis": "raquet",
    "snooker":"cue",
    ...
}

And the code would be this :

var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            var tbl = JSON.parse(httpRequest.responseText);
            $('select').on("change", function(){
                var t = tbl[$(this).val()];
                if (typeof t === "string") $('.sport').val(t);
            });
        }
    }
};
httpRequest.open('GET', 'things.json?time='+Date.now());
httpRequest.send(); 
like image 56
Denys Séguret Avatar answered Oct 04 '22 00:10

Denys Séguret