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/
The conditional loops that can be worked in a jQuery script are 'if' statement, 'if..else' statement, and 'if..else if' statement.
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.
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.
var selectedTab = $("#TabList"). tabs(). data("selected. tabs");
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With