How to delete a table line in angular js? - javascript

I`ve got a problem to delete items from object.
I made a function for deleting,but unfortunetly it can only delete 1 number in object.Like if i have 2 tasks and i choose to delete 2nd it will delete 1st one.
No idea how to fix it:(
$scope.deleteTask = function(taskIndex){
$scope.tasks.splice(taskIndex,1);
}
Here`s another code blocks for easier understanding of my code:
<tr ng-repeat="task in tasks">
<td>
<button class="btn btn-danger" ng-click="deleteTask(task)">Delete</button>
</td>
<td>{{task.taskName}}</td>
<td><input type="checkbox" ng-model="statusCheck"> </td>
<td style="{{setStyleToTd(statusCheck)}}">{{statusChecker(statusCheck)}}</td>
<td><button class="btn btn-primary">Edit</button></td>
</tr>
var taskInformation = [
{
taskName: "Test task"
, status: false
}
];
(I know there are lots of problems like mine but I didnt find a proper answer)

You should pass the id of the task not the task itself, try:
ng-click="deleteTask($index)"

It's better send object instead of index for delete. It should be like this
<button class="btn btn-danger" ng-click="deleteTask(task)">Delete</button>
$scope.deleteTask = function(task){
var taskIndex = $scope.tasks.indexOf(task);
$scope.tasks.splice(taskIndex,1);
}

Related

Having trouble sorting table with JQuery sort method

I am using PHP and JQuery to build a data table, I am using jQuery's .sort() method to sort the table. However, it is not working as excepted.
For the text fields, nothing is changed (except that the rows are rendered again).
For the numeric fields, the table sorts in a really weird manner.
Clearly the ID does not make sense like this? Here is my JavaScript code:
const rows = tbody.find('tr').sort((a, b) => {
let first, second;
if ($(e.target).attr('data-order') === 'asc') {
second = a;
first = b;
$(e.target).attr('data-order', 'desc');
}
else {
second = b;
first = a;
$(e.target).attr('data-order', 'asc');
}
const firstTd = $(first).children().eq($(e.target).attr('data-index') - 1).text();
const secondTd = $(second).children().eq($(e.target).attr('data-index') - 1).text();
// Take care of numbers
try {
return firstTd - secondTd;
}
catch (e) {
// Value is string
const value = firstTd.localeCompare(secondTd, "en");
return value;
}
}).appendTo(tbody);
Here is the source code for my table (I just added two rows):
<table class="table">
<thead>
<tr>
<th>
<button class="btn btn-light data-table-sort"
data-index="1" data-order="asc">
id <span class="fa fa-sort" aria-hidden="true"></span>
</button>
</th>
<button class="btn btn-light data-table-sort"
data-index="3" data-order="asc">
Text <span class="fa fa-sort" aria-hidden="true"></span>
</button>
</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>72</td>
<td>af7c16d8f1</td>
<td>2021-11-26 06:16:55</td>
<td>
<form method="POST">
<input type="hidden" name="id" value="72">
<input type="submit" name="action" value="Details"
class="btn btn-info">
<input class="btn btn-primary" name="action"
type="submit" value="Edit">
<input data-id="72"
class="btn btn-danger data-table-delete"
name="action" value="Delete" type="submit">
</form>
</td>
</tr>
<tr>
<td>7</td>
<td>bedd6af3ed</td>
<!-- The same form as previous row -->
</td>
</tr>
</tbody>
</table>
I have made sure that tbody contains the correct value. I am also selecting the correct column. The table has to be dynamic and reusable so I can't hardcode everything.
Note: I have already tried appending rows to the table instead of the <tbody> element.
You probably need to detach elements since you reattach it again later:
tbody.find('tr').detach().sort...
This may need readjustments depending on how jQuery arrays are returned but detaching elements is the main idea and other things should be pretty trivial.

Get data from dynamically added elements and pass to Django request.POST

I have a restaurant_form which allows user to input menu items. Each menu item represent a table row which is added dynamically. Each table row has input for: menu item, price, halal(Boolean), and notes.
Here is a sample entry. data-ids and names of input elements are incremented.
<tbody class="menu-entry ">
<tr id='menu0' data-id="0" class="hidden">
<td data-name="name" class="name">
<input type="text" name='name0' placeholder='Menu Item' class="form-control"/>
</td>
<td data-name="price">
<input type="text" name='price0' placeholder='0.00' class="form-control"/>
</td>
<td data-name="halal">
<input type="checkbox" name="veg0" value="halal" class="form-control">
</td>
<td data-name="notes">
<textarea name="notes0" placeholder="Contains soy." class="form-control"></textarea>
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'></button>
</td>
</tr>
</tbody>
What is the best way to retrieve data from the table? I have tried this:
$('#restaurant_form').submit(function () {
$('.menu-entry').each(function()
{
$(this).find('td').each(function(){
$(this).find("input").each(function() {
alert(this.value)
});
$(this).find("textarea").each(function() {
alert(this.value)
});
})
})
})
The alert() shows the correct values however I am wondering if there is a better way to do this?
Edit I simplified it using:
$('.menu-entry .form-control').each()
Also, after retrieving the values, how can I pass it to the view with a POST request? I would like to save the values to model
RestaurantMenu with columns name, price, halal and notes.
Thank you.
Here's what I did:
For every menu entry, I converted the values to a string separated by comma and added a hidden input to hold the value. I added class 'menu-row' to tr.
$('#restaurant_form').submit(function () {
$('.menu-row').each(function(){
var menu_entry = ""
$(this).find('.form-control').each(function(){
menu_entry = menu_entry + this.value + ","
})
$('#restaurant_form').append('<input type="hidden" name="menu_entries" value="'+ menu_entry +'" />')
alert(menu_entry)
})
})
In views.py :
menu_entries = request.POST.getlist('menu_entries')
for menu_entry in menu_entries:
entry = menu_entry.split(",")
if entry[1]:
price = round(float(entry[1]), 2)
else:
price = 0.00
if not entry[2]:
entry[2] = False
MenuItems.objects.create(name=entry[0], price=price, halal=entry[2], notes=entry[3], restaurant_id=r.id)
If anyone knows a better approach, I would love to know. Thank you!

Editable multiple forms on a table

I am using editable plugin to preform in place edit
This is the code I am using that I got from their Doc page, it is supposed to be used for adding new records, But I want to use it to modify records)
<script>
$(document).ready(function() {
//init editables
$('.myeditable').editable({
url: '/post',
placement: 'right'
});
//make username required
$('#new_username').editable();
//automatically show next editable
$('.myeditable').on('save.newuser', function(){
var that = this;
setTimeout(function() {
$(that).closest('td').next().find('.myeditable').editable('show');
}, 500);
});
//create new user
$('#save-btn').click(function() {
$('.myeditable').editable('submit', {
url: '/newuser',
ajaxOptions: {
dataType: 'json' //assuming json response
},
success: function(data, config) {
if(data && data.id) { //record created, response like {"id": 2}
//set pk
$(this).editable('option', 'pk', data.id);
//remove unsaved class
$(this).removeClass('editable-unsaved');
//show messages
var msg = 'New user created! Now editables submit individually.';
$('#msg').addClass('alert-success').removeClass('alert-error').html(msg).show();
$('#save-btn').hide();
$(this).off('save.newuser');
} else if(data && data.errors){
//server-side validation error, response like {"errors": {"username": "username already exist"} }
config.error.call(this, data.errors);
}
},
error: function(errors) {
var msg = '';
if(errors && errors.responseText) { //ajax error, errors = xhr object
msg = errors.responseText;
} else { //validation error (client-side or server-side)
$.each(errors, function(k, v) { msg += k+": "+v+"<br>"; });
}
$('#msg').removeClass('alert-success').addClass('alert-error').html(msg).show();
}
});
});
//reset
$('#reset-btn').click(function() {
$('.myeditable').editable('setValue', null)
.editable('option', 'pk', null)
.removeClass('editable-unsaved');
$('#save-btn').show();
$('#msg').hide();
});
});
</script>
And this is the html
<tr>
<td>adel</td>
<td></td>
<td></td>
<td></td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
<tr>
<td>sdqsd</td>
<td></td>
<td></td>
<td></td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
<tr>
<td>dzadz</td>
<td>from me with love</td>
<td>anywhere</td>
<td>http://justawebsite.com</td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
Now everything works fine, Except if I edit one of the 2 first rows and hit Ok It will send the details of the last form http://justawebsite.com and sometimes it doesn't send anything, It is really messed up and I spent hours reading te documentation but I couldn't figure out the problem
As I said in my comment, you've got different elements with the same id, so the selectors won't work (id must be unique). Put them as class instead:
<tr>
<td>
adel
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
<a href="#" class="myeditable picture" data-type="text" data-name="picture" data-original-title="Enter Picture">
<img src="" />
</a>
</td>
<td width="10%">
<button class="btn btn-primary btn-sm save-btn">Ok</button>
<button class="btn btn-sm pull-right reset-btn">Reset</button>
</td>
</tr>
Here's a fiddle to get you started https://jsfiddle.net/virginieLGB/k2of9xor/1/
On there, you'll see that I've selected the editable elements you want to submit.
$('.save-btn').click(function() {
var that = $(this);
var allEditables = that.parents("tr").find(".myeditable"); // all ".myeditable" elements in the same "tr" as the ".save-btn" that was clicked on
allEditables.each(function() {
// here I've kept your code because I don't know what happens in your file, but maybe you need a bulk action
$(this).editable('submit', {
...
I don't know how your PHP file works, so don't know how you save your user and if you need to submit all fields at once or not. If so, you'll have to modify my answer a bit.
Have you tried refreshing it afterwards?
For me i noticed, that as soon as it was refreshed i got the result that i have been expecting, but only for one of them. However, i couldn't solve the problem yet.
Please let me know what kind of result you get.
Otherwise try debugging...disable one of the first rows and try it again..

How to add Data to Specific index of json array using angularjs

I was created table data and edit button and i am getting problem when i was trying to add edit data to specific row.
Here my plunkr :- http://plnkr.co/edit/QKz7nu458i8Il4OLmAyw?p=preview
Here HTML page
<table class="table table-bordered">
<thead>
<tr>
<th><input type='checkbox' ng-modal='isall' ng-click='selectallrows()'></th>
<th>ID</th>
<th>Name</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='p in person' ng-class="{'success':tableselection[$index]}">
<td><input type='checkbox' ng-model='tableselection[$index]'></td>
<td>{{p.id}}</td>
<td>{{p.name}}</td>
<td><button class='btn btn-primary' ng-click='edit(p.id)'><span class="glyphicon glyphicon-pencil"></span>Edit</button></td>
</tr>
</tbody>
</table>
<div ng-show='editabledata'>
<form role='form' class='form-horizontal'>
<div class='form-group'>
<label>Id :-</label>
<input type='text' ng-model='pid' class='from-group col-sm-2'></div>
<div class='form-group'>
<label>Name:-</label>
<input type='text' ng-model='pname' class='from-group col-sm-2'>
</div>
<button class='btn btn-primary' ng-click='saveeditdata(pid)'>Save</button>
<button clas='btn btn-primary' ng-click='canceleditdata()'>Cancel</button>
</form>
</div>
Here my .js
$scope.person=[
{id:1,name:'devendher'},
{id:2,name:'Macha'},
{id:3,name:'Macha devendher'}
];
$scope.editabledata=false;
$scope.edit=function(id){
$scope.editabledata=true;
for(i=0;i<$scope.person.length;i++){
if($scope.person[i].id==id)
{
$scope.pid=$scope.person[i].id;
$scope.pname=$scope.person[i].name;
}
}
}
$scope.saveeditdata=function(id){
for(i=0;i<$scope.person.length;i++){
if($scope.person[i].id==id){
$scope.person[i].push({'id':$scope.pid,'name':$scope.pname})
}
}
}
i got error " $scope.person[i].push " is not a function
Is there any alternate way to add data to specific index of array?
I think you mean:
$scope.person.push({...})
Or
$scope.person[i] = {...}
This is very over complicated and you aren't taking advantage of using a single object for the form data. In addition you are using different property names for the editing vs original object. All the loops you are doing are unnecessary
Much simpler steps:
To edit object, pass whole object to controller function :
<button ng-click='edit(p)'>
In controller make copy of object and store reference to the selected one to update later
$scope.edit=function(person){
$scope.editabledata = true;
$scope.selectedItem = person;
$scope.editItem = angular.copy(person);
}
In edit form use full object reference in ng-model. No need to create individual variables, use the properties that already exist
ID : <input ng-model="editItem.id">
Name: <input ng-model="editItem.name">
In the save function extend the original object with the updated one
$scope.saveeditdata=function(){
// merge updates
angular.extend($scope.selectedItem , $scope.editItem);
// reset
$scope.editabledata = false;
$scope.editItem = {};
}
For delete see : How do I delete an item or object from an array using ng-click?
DEMO

Sending arrayList index to a ajax function in Thymeleaf

I have the following list in my Jsp page.Each row in the list is accompanied by a button.
When I click om that button I need to pas the row index to the controller.
<tr th:each="idBean : ${idBeanLst}" >
<td th:text="${idBeanStat.count}" id="count"></td>
<td th:text="${idBean.identifierId}" id="idenId"></td>
<td th:text="${idBean.idNumber}" id="idNumber"></td>
<td th:text="${idBean.issueLocation}" id="issueLocation"></td>
<td th:text="${idBean.issueDate}" id="issueDate"></td>
<td th:text="${idBean.expiryDate}" id="expDt"></td>
<td><button type="button" name="identifierRow" id="identifierRow" th:value="${idBeanStat.index}" onclick="doAjaxCallRemoveIdentifier(${idBean.index})">Remove</button>
</td>
function doAjaxCallRemoveIdentifier(id) {
alert(id);
//do ajax call to the controller..
}
But I am not able to pass the row id .Any help is much appreciated.
This is what worked for me
<button type="button" name="identifierRow" id="identifierRow" th:value="${idBeanStat.index}" th:onclick="'javascript:doAjaxCallRemoveIdentifier(\'' + ${idBeanStat.index} + '\');'">Remove</button>
Thanks to #ohiocowboy for suggesting me to use th:onclick.Hope this helps some one else.
See 6.2 of the docs. http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html
${idBean.index} will get you the index

Categories

Resources