jquery - Strange behaviour with loop in Javascript -
i've got table-like structure text inputs in trying make entire row removed children, first passing values of cells 1 one in rows below keep ids numbering structure.
the table structure this:
<table cellpadding=0> <tr id="myrow1"> <td id="#r1c1"> <input class="mycell"> </td> <td id="#r1c2"> <input class="mycell"> </td> <td id="#r1c3"> <input class="mycell"> </td> <td id="#r1c4"> <input class="mycell"> </td> </tr> <tr id="myrow2"> <td id="#r2c1"> <input class="mycell"> </td> <td id="#r2c2"> <input class="mycell"> </td> <td id="#r2c3"> <input class="mycell"> </td> <td id="#r2c4"> <input class="mycell"> </td> </tr> <!-- ...and on. --> </table>
having table, when event triggered,i make code run:
var rows = 1; // value updated when adding/removing line //this code runs <tr> event keyup if (event.altkey) { // define here alt+somekey actions. // getting position values var currentid = $(this).attr('id'); var row = number(currentid.split('c')[0].substring(1)); var column = number(currentid.split('c')[1]); var belowval; if (event.which == 66) { //case ctrl+b // if not last row, start looping if (rows > row) { var diff = rows - row; // iteration on rows below (var = 0; < diff; i++) { // iteration on each column (var c = 1; c <= 4; c++) { // here try value column below belowval = $('#r'+(row+1+i).tostring() + 'c'+c.tostring()).val(); $('#r'+(row+i).tostring()+'c' + c.tostring()).find('.mycell').val(belowval); } } } $('#myrow'+rows.tostring()).empty(); $('#myrow'+rows.tostring()).remove(); rows--; } }
it works fine removing last row, but, when trying remove upper row, values of current row , ones below become blank instead of moving up. made code each row below pass it's values upper row, isn't doing wanted.
why happening? couldn't figure out.
the problem seem be, ids using access values not ids of input elements, rather ids of containing table cells.
here approach, doesnt use ids, relies on nodes structure instead, code not tested:
if (event.which == 66) { var currentrow = $(this); var currentinputs = currentrow.find('input.mycell'); while(var nextrow = currentrow.next('tr')) { var nextinputs = nextrow.find('input.mycell'); currentinputs.each(function(index,element){ element.val(nextinputs.get(index).val()); }); currentrow = nextrow; currentinputs = nextinputs; } currentrow.remove(); }
Comments
Post a Comment