A simple check if selected, if not add to array in Javascript -
this function supposed take id of selected row , check see if in array or not, if isn't on array, add array, otherwise remove array. problem can't seem order of events right. loop not run way through (because of breaks) if remove breaks, while image changing (checkbox) works, array still wrong.
i don't understand why despite declaring deletestring = [];
outside of function, without putting inside function, call of deletestring.push(orderid);
fails
it seems obvious problem, on first run regardless of how big array is, whether or not check matches or doesn't match, rest of loop won't run. perhaps should check wait until loop done before using result of found/not-found.
function passselection(orderid) { // check if empty if (deletestring.length == 0) { // turn array deletestring = []; // first entry deletestring.push(orderid); // mark row checked $("#"+"select-box-"+orderid).attr('src', 'images/red-checked.png'); } else { // not first order // check if in array // length of array var delstrlen = deletestring.length; // loop through array (var = 0; < delstrlen; i++) { if (deletestring[i] == orderid) { // match found, remove deletestring array deletestring.splice(i, 1); // update row $("#"+"select-box-"+orderid).attr('src', 'images/unchecked.png'); break; } else { // not in array // add array deletestring.push(orderid); // update row $("#"+"select-box-"+orderid).attr('src', 'images/red-checked.png'); break; } } } }
you ought use indexof test existence of elements in array. indexof returns position of search-item or -1 if element cannot found so, here code have refactored , tested
var deletestring = []; function passselection(orderid) { // check if empty let orderpos = deletestring.indexof(orderid); if (orderpos == -1) { // first entry deletestring.push(orderid); // mark row checked $("#"+"select-box-"+orderid).attr('src', 'images/red-checked.png'); } else { // match found, remove deletestring array deletestring.splice(orderpos, 1); // update row $("#"+"select-box-"+orderid).attr('src', 'images/unchecked.png'); } }
Comments
Post a Comment