I am using jQuery to take data from an xml file and save it to a string. The string is a switch statement which I want to become a function.
$.get('type.xml', function(xml) {
var cases=[];
$(xml).find('type').each(function(){
index=parseInt($(this).find('earn').text());
if($.isArray(cases[index])){
cases[index].push($(this).find('name').text());
}else{
arr=$.makeArray($(this).find('name').text());
cases[index]=arr;
}
});
var autoearn="function(x){switch(x){";
for(i=0;i<=100;i+=5){
if($.isArray(cases[i])){
$.each(cases[i], function(index,v){
autoearn+='case "'+v+'":';
});
autoearn+='$("input[name^=\'earn\']").val('+i+');break;';
}}
autoearn+='}}';
});
The first section makes a 2D array that associates an array of cases to their resultant output by their index. So that something that earns $10 (e.g. Meeting) will be stored in cases[10] (Meeting=cases[10][0]).
The second part writes a string that makes a puts into a switch statement that looks something like this:
function(x){
switch(x){
case "Meeting":
$("input[name^='earn']").val(10);
break;
case "Event1":
case "Event2":
$("input[name^='earn']").val(20);
break;
}
}
Note that the syntax for the switch cases make Event1 and Event2 have the same result.
Now autoearn is just a string that has the code for the function I want. How do make into a function? Is there a better way to do this? I'm thinking of sending it through PHP to return it back to jQuery but this whole thing seems really indirect and there is probably an easier way to do this.