Emily Graham
Emily Graham

Reputation: 17

javascript code does not execute after a loop

I have the following code (snippet from a larger function):

var res = data.results;
for (var i=0;i<res.length;i++) {
    $('<option value="' + res[i] + '">' + res[i] + '</option>').appendTo(sel);
}
if (data.select && data.select!='') { sel.val(data.select); } 

For some reason, the

if (data.select && data.select!='') { sel.val(data.select); } 

line just wasn't executing, and is appearing greyed out in Firebug suggesting that Firebug somehow knows it is not reachable. If I make a simple change to the code like this:

var res = data.results;
for (var i=0;i<res.length;i++) {
    var opt = '<option value="' + res[i] + '">' + res[i] + '</option>';
    $(opt).appendTo(sel);
}
if (data.select && data.select!='') { sel.val(data.select); }

the last line runs without issue.

I found similar post on here where the for loop had a <= for the while parameter causing an error and although this is not the case here, when I stepped through the code it was trying to execute the loop one more time than it should have, i.e. if res.length was 4, it was allowing i to increment to 4 and then trying to execute the code in the loop which was therefore ending the code because res[i] was out of range, even though it wasn't placing an error in the console. If I change the code as demonstrated, the loop does not run when i == res.length

So, how did Firebug know that the original code wasn't going to allow execution past the end of the loop, and why is the loop executing one more time than it should?

The entire function is below and is a success callback from a jQuery ajax call which populates a select with the values received from the server:

function GetDeptsOK(data, textStatus, jqXHR) {
    var sel = $('#orgpicker').find('select[name="orgpicker-dept"]');
    if (sel.length == 0) {
        var cell = $('#orgpicker-deptcell');
        cell.text('');
        $('<select name="orgpicker-dept"></select>').appendTo(cell);
        sel = $('#orgpicker').find('select[name="orgpicker-dept"]');
    } else {
        sel.find('option').remove();
    }
    $('<option value=""></option>').appendTo(sel);
    var res = data.results;
    for (var i=0;i<res.length;i++) {
        $('<option value="' + res[i] + '">' + res[i] + '</option>').appendTo(sel);
    }
    if (data.select && data.select!='') { sel.val(data.select); }
} 

Upvotes: 0

Views: 747

Answers (1)

Array out of bound
Array out of bound

Reputation: 1133

replace this by

var res = data.results;
for (var i=0;i<res.length;i++) {
    if(!res[i])
       break;
    var opt = '<option value="' + res[i] + '">' + res[i] + '</option>';
    $(opt).appendTo(sel);
}
if (data.select && data.select!='') { sel.val(data.select); }

Upvotes: 1

Related Questions