Reputation: 1618
I have a form that has some pre populated fields. The data and ID values for these fields are pulled from a database.
The user has the option to add, edit or delete the rows, and the save the results. To save pushing numerous values back I'm adding to an array only the entries that have changed, are new or are marked to be deleted and then sending those back to my php page.
The form fields look like this :
<tr>
<td>
<input name='id[]' type='hidden' value='123456789'/>
<input name="site[]" type="text" value='123'/>
</td>
<td><input name="location[]" type="text" value='NW'/></td>
<td><a href='#' name="deleteRow"/>x</td>
</tr>
The array is called rows[]
and looks like this: "mode:ID:A:B"
["del:123456789:0:0", "del:99887766:0:0", "edit:1471872633890:8845:0", "add:4875125862:1523:NE"]
If a user marks a row for deletion an entry similar to this is added to the array:
"del:99887766:0:0"
If the user adds a new row an entry similar to this is added to the array:
"add:1471938503:0:0"
and if an entry is edited the entry add to the array looks like:
"edit:1471872633890:8845:0"
This all seems to work upto a point..
When a user edits an entry I'm using the following to check the array and update the array entry where an ID matches. So if they edit the same value multiple times there is only one copy in the array.
var id = $(this).closest('tr').find('input[name="id[]"]').val()
var site = $(this).closest('tr').find('input[name="number[]"]').val()
var location = $(this).closest('tr').find('input[name="description[]"]').val()
var res = 'edit:' + id + ':' + site + ':' + location;
rows = rows.map(function(value) {
if( value.indexOf(id) > -1 ) {
return res;
}
return value;
});
if ($.inArray(res, rows) == -1) {
rows.push(res)
}
Again this seems to work, but I have an issue..
When a new row is added, an entry is added to the array as: "add:1471938503:0:0"
but when the user then edits it, the entry changes to have the mode of edit
NOT add
How can I code this so a new entry has the mode of add
and stays as add
even if it is edited. A del
stays as del
and a edit
stays as edit
I have tried :
var res = 'edit:' + id + ':' + site + ':' + location;
var resAdd = 'add:' + id + ':' + site + ':' + location;
rows = rows.map(function(value) {
if( value.indexOf('add:'+id) > -1 ) {
return resAdd;
} else {
return resEdit;
}
return value;
});
But that just messed everything up !!
Any ideas how I can do this ? I have created a codepen.. but it doesn't seem to want to run..
Thanks
Upvotes: 1
Views: 37
Reputation: 12452
You can check this in your map
function an prepend the correct action in front of res
.
var res = ':' + id + ':' + site + ':' + location;
rows = rows.map(function(value) {
if( value.indexOf(id) > -1 ) {
return (value.indexOf('add') === 0 ? 'add' : 'edit') + res;
}
return value;
});
Or even possible to check with substr
:
return (value.subtr(0, 3) === 'add' ? 'add' : 'edit') + res;
Upvotes: 1