I’m not sure if this is even what you call it, but basically, I am grabbing a list of cities that is stored in one key in local storage. I am splitting them by comma, and then dynamically checking the checkboxes with the corresponding values for the id. Now I want to have any number of cities in there so I don’t want to check the boxes individually like [0], [1] etc but is there there like a unlimited way to do this or something. Sorry if this isn’t clear..Ill post my code below, My code below is checking the boxes from keys 0-5, I want to be able to do 0 – unlimited , so to speak. Any help is appreciated.
<script type="text/javascript">
var refreshId = setInterval(function()
{
var citySplit = localStorage.getItem("city2");
var myResult = citySplit.split(",");
$("#"+myResult[0]+"").prop("checked", true);
$("#"+myResult[1]+"").prop("checked", true);
$("#"+myResult[2]+"").prop("checked", true);
$("#"+myResult[3]+"").prop("checked", true);
$("#"+myResult[4]+"").prop("checked", true);
$("#"+myResult[5]+"").prop("checked", true);
}, 6500);
</script>
Many ways to do this:
NOTE: All of these examples are untested.
Simple
while-loop – 0, 1, 2, 3, 4Simple
for-loop – 0, 1, 2, 3, 4jQuery.eachmethod with callback usingthisor
jQuery.eachmethod with callback usingarguments[1](value)while-loop from behind 4, 3, 2, 1, 0for-loop from behind 4, 3, 2, 1, 0while-loop popping array This destroys the array from behind 4, 3, 2, 1, 0or
while-loop shifting array This destroys the array from the start 0, 1, 2, 3, 4???
As you can see there is many ways to dealing with arrays.
For simple thing I will recommend you to use one of the two first methods.
The
jQuery.eachmethod is very nice because you get a the key and value of the array in a local scope. (key = 0, 1, 2, 3, 4, …) (value = what evermyResult[key]is).The two where we destroy the array is also very nice. But I will not recommend you not to use these before you understand more simple methods. As situation i can think of using this method is if you have to load a lot of files or initialize a lot of functions in a specific order: