Add and remove grid rows according to form input

Hi,
I have a form with an input field and a grid. I want that the number of rows equals the integer specified on the form input field.
I’m using a data processor but sending all form data and grid data using a submit button.
This is the function:

    myform.getInput("cantidadint").onchange = function() {
                   var nlineas=mygrid.getRowsNum();
                    var cint= myform.getItemValue("cantidadint");
                    var e = cint-nlineas;
                            for (var i = e; i > 0; i--){
                                            mygrid.addRow(i,[0,'new']);
                            }
                            for (var i = e; i < 0; i++){
                                    mygrid.deleteRow(mygrid.getRowId(mygrid.getRowsNum()-1));
                            }
            };

The problem is when I input a lower number after the initial one it only deletes 1 row.
This happens when the grid is not loaded.
The intention is to have a public form, so the grid must not be loaded.
Can you help me with this issue?
Thanks in advance