Reputation: 6155
Okay, so I have the following form fields:
1. [] [] [] x
2. [] [] [] x
3. [] [] [] x
4. [] [] [] x
[rand]
I allow the user to insert random numbers into the forms by clicking "rand":
1. [01] [09] [12] x
2. [03] [12] [13] x
3. [12] [15] [16] x
4. [01] [02] [03] x
[rand]
If the user so desires, they can delete a row and add a new one
1. [01] [09] [12] x
3. [12] [15] [16] x
4. [01] [02] [03] x
5. [] [] [] x
[rand]
Each row is named by its fields:
1. [01] [09] [12] = name=row_name[1][0], row_name[1][0], row_name[1][0]
3. [12] [15] [16] = name=row_name[3][0], row_name[3][0], row_name[3][0]
4. [01] [02] [03] = name=row_name[4][0], row_name[4][0], row_name[4][0]
5. [] [] [] = name=row_name[5][0], row_name[5][0], row_name[5][0]
[rand]
The problem I face is when a user deletes a number of rows, the sequences are now out of order, so instead of: 1,2,3,4 I have: 1,3,4,5
This means my random function will not work on row 5 since it is looking for 1,2,3,4 (in a for loop).
So my dilemma is how best to code this...
On the one hand, I am thinking of re-naming the fields each time a user deletes a row to keep them in sequence: 1,2,3,4
On the other hand I am thinking that I could just ignore the missing fields and improve how I insert the numbers.
The rand function works as follows:
var numbers_per_row = 3;
var total_numbers = 4;
var rows = getRandomNumbers(numbers_per_row,total_numbers);
This returns an array: [
0 => [01,09,12],
1 => [03,12,13],
2 => [12,15,16],
3 => [01,02,03]
]
Now that I have the array, I next need to insert the random numbers into the form fields:
var total_rows = rows.length();
for (var 1 = 0; i < total_rows; i++) {
var line = row[i];
for (var x =0; x < numbers_per_row; x++) {
var field_name = 'row_name['+(i+1)+']['+x+'];
$("#formName input[ name='" + field_main + "' ]").val(line[x]);
}
}
Unfortunately this function does not take into account the missing values that were deleted.
I have been pondering the most logical way to go about this. Any ideas?
Upvotes: 1
Views: 91
Reputation: 6155
The answer to this questions was pretty simple, thanks to Nina for the suggestions, this is what I did:
Simple :)
Upvotes: 1
Reputation: 386560
Take an array with the row numbers and delete the number if the row is being deleted. When a new row is inserted, add the row number to the array.
In this way, it is possible to iterate over the array with the row numbers and keep a working system.
Upvotes: 1