I have a function that is repeated a few times, and I believe it is possible to simplify and send variables from an array.
var i = masterdata.timing.split(',');
var index = 0;
for (index = 0; index < i.length; ++index) {
$("#timing_" + i[index].trim()).prop('checked', true);
}
var i = masterdata.concern.split(',');
var index = 0;
for (index = 0; index < i.length; ++index) {
$("#concern_" + i[index].trim()).prop('checked', true);
}
var i = masterdata.steps.split(',');
var index = 0;
for (index = 0; index < i.length; ++index) {
$("#steps_" + i[index].trim()).prop('checked', true);
}
Maybe just change the categories into a variable and send the catergories from an array?
var chkgroup = [
'timing, concern, steps'
]
For example, if we have an array and want to output each element in the array, rather than using the index number to do so one by one, we can simply loop through and perform this operation once. There are numerous methods for looping through an array in JavaScript.
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
As already mentioned, you can iterate through an array using the length attribute. The loop for this will iterate through all the elements one by one till (length-1) the element is reached (since arrays start from 0). Using this loop you can search if a specific value is present in the array or not.
Your idea should work fine:
var i;
var index = 0;
var j = 0;
var chkgroup = ['timing', 'concern', 'steps'];
var currentGroup;
for (j = 0; j < chkgroup.length; ++j) {
currentGroup = chkgroup[j];
i = masterdata[currentGroup].split(',');
for (index = 0; index < i.length; ++index) {
$("#" + currentGroup + "_" + i[index].trim())
.prop('checked', true);
}
}
If the chkgroup
array really matches the object keys
in masterdata
, you could use an outer for..in
loop instead:
var i;
var index = 0;
var currentGroup;
for (currentGroup in masterdata) {
i = masterdata[currentGroup].split(',');
for (index = 0; index < i.length; ++index) {
$("#" + currentGroup + "_" + i[index].trim())
.prop('checked', true);
}
}
Note that there's no order defined for for...in
, so if you need to guarantee that you're iterating over the object properties in a certain order, it might be better to use the predefined array.
You could also get fancy with $.map
:
var values = $.map(masterdata, function (i, currentGroup) {
return $.map(i.split(','), function (val) {
return $('#' + currentGroup + '_' + val.trim());
});
});
$(values).prop('checked', true);
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