Managing IF Mass Expression in jQuery

I have an if statement that has over 100 different ifs.

per minute im using something like 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 the user selects "London" from the drop-down list, the next field is populated with the zip code for London.

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

Is it possible to create an xml file for this? or could we put each graph and its value in an object inside the array and configure it that way?

Any help is much appreciated, thanks

http://jsfiddle.net/4xQeX/

+6
source share
1 answer

A common solution is to store your sports / facility pairs as data, as 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 can even get tbl from a separate JSON file (or just save it in another JS file) for easier management.

Suppose you want to use a separate JSON file called things.json , then your file will look like this:

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

And the code will be like 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(); 
+24
source

Source: https://habr.com/ru/post/951717/


All Articles