can you please tell me why my row is not deleted.I I make a demo in which I added the student name .I am able to add the student name .Now I have two issue I am not able to delete row and Edit.can you please tell where i am wrong ?
here is my demo
http://plnkr.co/edit/1lem6t4h7b6Eefsz32t6?p=preview
app.controller("studentcntr",['$scope',function(scope){
scope.studentDetail=[];
scope.addStudent=function(){
bootbox.prompt("Enter Name!",function(res){
console.log(res);
if(res==null){
}else {
scope.studentDetail.push({ name: res });
}
scope.$digest();
});
};
scope.editRowName=function (name) {
// body...
// alert(name);
setTimeout(function() {
$('.bootbox-input').val(name);
}, 10);
}
scope.deleteRow=function (id) {
// body...
alert('s'+id)
$('#'+id).remove();
}
}])
I am able to delete row .But problem is that when I remove row and add new name it create again delete row why ? why it is now delete permanently
why it is now delete permanently
As you are not deleting it from scope.studentDetail it is persisting.
Changes
HTML
<td ><button ng-click="editRowName(student)">Edit</button></td>
<td ><button ng-click="deleteRow($index)" >Delete</button></td>
Script
scope.editRowName=function (student) {
bootbox.prompt({
title: "What is your name?", //Title
value: student.name, //Pre-filled name
callback: function(result) {
student.name = result; //Update name
scope.$digest();
}
});
}
scope.deleteRow=function ($index) {
scope.studentDetail.splice($index, 1);
}
DEMO
The problem was that you were removing the element from DOM and not from the data model..
http://plnkr.co/edit/a4WLy1ckQHT68uz1CGeh?p=preview
It works for both edit and delete.
<td><button ng-click="editRowName($index, student.name)">Edit</button></td>
<td><button ng-click="deleteRow($index)" >Delete</button></td>
and in the controller
scope.editRowName=function (index, name) {
scope.currentIndex = index;
bootbox.prompt("Enter New name for " + name,function(res){
console.log(res);
if(res==null){
}else {
if (scope.currentIndex === -1) {
scope.studentDetail.push({ name: res });
} else {
scope.studentDetail[scope.currentIndex].name = res;
scope.currentIndex = -1;
}
}
scope.$digest();
});
}
scope.deleteRow=function (id) {
scope.studentDetail.splice(id, 1);
}
Related
I have a variable in my jQuery called storedDealer that I want to be filled with the option text when a drop-down item is selected:
var storedDealer = '';
$(document).ready(function () {
let dealerId = #Model.DealerID;
if (0 < dealerId.length) {
$("#DealerID option[value='dealerId'']").attr('selected', 'selected');
$('#dealershipName').val(storedDealer);
}
$('#DealerID').on("change", function () {
storedDealer = this.value;
});
});
function getDealers(el) {
$.get("#Url.Action("GetDealers", "Admin")?region=" + $(el).val(), function (res) {
var markup = "";
for (var i = 0; i < res.length; i++) {
markup += '<option value='+res[i].Value+'>'+res[i].Text+"</option>"
}
$('#DealerID').prop('disabled', false);
$("#DealerID").html(markup).show();
});
}
My HTML has a little bit of C# Razor code that is the only place the DealerID is defined. I have added the <var id="dealershipName"> item:
<tr>
<td align="right">Dealership:</td>
<td>#Html.DropDownListFor(m => m.DealerID, new List<SelectListItem>())</td>
<td><var id="dealershipName" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
I would not have thought the Razor variables would be visible by jQuery, but they somehow seem to work.
But when the search is submitted, the page refreshes. Now the drop-down list is reset and the <var> field is blank.
That <var> field is what I added, and I am trying to get to work.
How can I get the value to stay after the form reloads?
I think you can try to use Session,here is a demo for .net6.Each time the slected value is changed,change storedDealer and the session data.And when you refresh the page,if the session data is not null,storedDealer will be set with the session data:
Program.cs:
builder.Services.AddControllersWithViews();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(1);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
actions:
public IActionResult Test(){
return View();
}
public void SetSession(string storedDealer) {
HttpContext.Session.SetString("storedDealer", storedDealer);
}
Test view:
var storedDealer = "";
$(document).ready(function () {
let dealerId = #Model.DealerID;
if (0 < dealerId.length) {
$("#DealerID option[value='dealerId'']").attr('selected', 'selected');
if(storedDealer==""&&"#(string.IsNullOrEmpty(Context.Session.GetString("storedDealer")))"!=True)
{
storedDealer = "#Context.Session.GetString("storedDealer")";
}
$('#dealershipName').val(storedDealer);
}
$('#DealerID').on("change", function () {
storedDealer = this.value;
$.ajax({
type: "GET",
url: "SetSession",
data: {storedDealer:$("#IdSelectIdEmpleado").val()},
});
});
});
In my website i am listing movies and tv series that users can share their comments on them. Users can add comments, but when it comes to receiving comments, an undefined value is returned. (I am trying to get comments from movieComment. movieComment store comments for the movie)
var show = qs["movieId"];
/* show variable is giving my movie's ID and it is 1 */
btnComment.addEventListener('click', (e) => {
var movieComment = document.getElementById('textComment').value;
push(child(firebaseRef, 'Movies/' + show + '/movieComment/'), movieComment) {
movieComment: movieComment
};
});
function AddItemsToTable2(comment) {
const comments = `
<td>Alan Smith</td>
<td><i class="fa fa-star" style="color:rgb(91, 186, 7)"></i></td>
<td>${comment}<h6>[May 09, 2016]</h6></td>
`;
html = comments;
body2.innerHTML += html;
}
}
function AddAllItemsToTable2(TheComments) {
body2.innerHTML = "";
TheComments.forEach(element => {
AddItemsToTable2(element.movieComment);
});
}
function getAllDataOnce2() {
var show = qs["movieId"];
get(child(firebaseRef, 'Movies/' + show + '/movieComment')).then((snapshot) => {
var comments = [];
comments.push(snapshot.val());
console.log(comments);
AddAllItemsToTable2(comments);
});
}
window.onload = (event) => {
getAllDataOnce2();
};
Console.log(movies)
Undefined error:
Focusing on this function:
function AddAllItemsToTable2(TheComments) {
body2.innerHTML = "";
TheComments.forEach(element => {
AddItemsToTable2(element.movieComment);
});
}
The TheComments object here is a Record<string, string>[]:
TheComments = [{
"-Mstwhft8fKP6-M2MRIk": "comment",
"-Mstwj5P2TD_stgvZL8V": "a comment",
"-MstwjxvmkNAvWFaIejp": "another comment"
}]
When you iterate over this array, you end up with an element object that doesn't have a movieComment property, which is why when you feed it to AddItemsToTable2 you get undefined.
To fix this, you need to change the way you assemble the TheComments object:
function AddAllItemsToTable2(TheComments) { // TheComments: ({id: string, text: string})[]
body2.innerHTML = "";
TheComments.forEach(commentObj => AddItemsToTable2(commentObj.text));
}
function getAllDataOnce2() {
const show = qs["movieId"];
get(child(firebaseRef, 'Movies/' + show + '/movieComment'))
.then((snapshot) => {
const comments = [];
snapshot.forEach(childSnapshot => {
comments.push({
id: childSnapshot.key, // store this for linking to database/anchors
text: childSnapshot.val()
});
});
console.log(comments);
AddAllItemsToTable2(comments);
});
}
As another point, beware of XSS risks when using innerHTML and use innerText where possible for any user generated content. Also, you should wrap your comment content in a table row so comments are concatenated properly.
function AddItemsToTable2(commentObj) {
const commentEle = document.createElement('span');
commentEle.id = `comment_${commentObj.id}`;
commentEle.innerText = commentObj.text;
const commentRowHTML = `
<tr>
<td>Alan Smith</td>
<td><i class="fa fa-star" style="color:rgb(91, 186, 7)"></i></td>
<td>${commentEle.outerHTML}<h6>[May 09, 2016]</h6></td>
</tr>`;
body2.innerHTML += commentRowHTML;
}
function AddAllItemsToTable2(TheComments) {
body2.innerHTML = "";
TheComments.forEach(commentObj => AddItemsToTable2(commentObj));
}
With the above code block, you can now add #comment_-MstwjxvmkNAvWFaIejp to the end of the current page's URL to link to the "another comment" comment directly similar to how StackOverflow links to comments.
I'm working with list of checkboxes and I have next logic behavior for it:
if all items selected, checkbox "select all" is checked
if one of all selected items has been unchecked, checkbox "select all" is unchecked as well
This logic is clear. Depends of what item is checked I extract its id to an additional array and then using this array for request that to get data.
For pushing everything works fine, but for slicing the logic is strange. So I can slice the array until first item is checked, however I unchecked the first item, pushed and sliced items no more related with checkboxes.
I have reproduced plunker with it, so I appreciate if anybody could help me to find what I'm missing.
$scope.modelClass = {
selectedAll: false
};
$scope.selectAllClass = function (array) {
angular.forEach(array, function (item) {
item.selected = $scope.modelClass.selectedAll;
$scope.param =''
});
};
$scope.checkIfAllClassSelected = function (array) {
$scope.modelClass.selectedAll = array.every(function (item) {
return item.selected == true
});
$scope.checked = array.filter(function (item) {
return item.selected == true
}).length;
angular.forEach(array, function (obj) {
if(obj.selected == true){
requestClass(obj)
}
});
};
var selectedClass = [];
var requestClass = function (obj) {
selectedClass.push(obj);
angular.forEach(selectedClass, function (val) {
if (val.selected != true) {
selectedClass.splice(selectedClass.indexOf(val.id), 1);
}
else {
selectedClass = selectedClass.filter(function (elem, index, self) {
return index == self.indexOf(elem);
})
}
});
$scope.param = _.map(selectedClass, 'id')
};
$scope.classes = [
{"id":4,"name":"Achievement","selected":false},
{"id":13,"name":"Information","selected":false},
{"id":6,"name":"Issue","selected":false},
{"id":5,"name":"Message","selected":false},
{"id":9,"name":"Request","selected":false}
]
The logic looks good for me, not sure what's wrong here. I've took the first solution from this post (it looks like you are using the second one) and slightly modified it for your needs.
$scope.model = {
selectedClass : []
}
$scope.isSelectAll = function(){
$scope.model.selectedClass = [];
if($scope.master){
$scope.master = true;
for(var i=0;i<$scope.classes.length;i++){
$scope.model.selectedClass.push($scope.classes[i].id);
}
}
else{
$scope.master = false;
}
angular.forEach($scope.classes, function (item) {
item.selected = $scope.master;
});
$scope.param = $scope.model.selectedClass
}
$scope.isChecked = function() {
var id = this.item.id;
if(this.item.selected){
$scope.model.selectedClass.push(id);
if($scope.model.selectedClass.length == $scope.classes.length ){$scope.master = true;
}
} else {
$scope.master = false;
var index = $scope.model.selectedClass.indexOf(id);
$scope.model.selectedClass.splice(index, 1);
}
$scope.param = $scope.model.selectedClass
}
$scope.classes = [
{"id":4,"name":"Achievement","selected":false},
{"id":13,"name":"Information","selected":false},
{"id":6,"name":"Issue","selected":false},
{"id":5,"name":"Message","selected":false},
{"id":9,"name":"Request","selected":false}
]
html
<div ng-class="{'selected': master, 'default': !master}">
<div>
<input type="checkbox" ng-model="master" ng-change="isSelectAll()" > Select all
</div>
</div>
<div ng-repeat="item in classes | orderBy : 'id'" ng-class="{'selected': item.selected, 'default': !item.selected}">
<div >
<input type="checkbox" ng-model="item.selected" ng-change="isChecked()">
{{ item.name }}
</div>
</div>
this is fixed plunker
I am using Asp.Net MVC4 and mongoDB connection. This is my controller :
public ActionResult Delete(string id)
{
var query = from n in ObjectMongoCollection.AsQueryable<User>()
where n.UserId.ToString() == id
select n;
User user = query.FirstOrDefault();
if (user == null)
{
ViewBag.Status = "0";
}
else
{
ObjectMongoCollection.Remove(Query.EQ("_id".ToString(), id));
ViewBag.Status = "1";
}
return View();
And I want to pass this id parameter as the id of selected row of this table :
#foreach (User usr in records)
{
<tr id="#usr.UserId">
<td>
#usr.Name
</td>
<td>
#usr.Surname
</td>
<td>
#usr.Number
</td>
</tr>
}
</tbody>
</table>
<div class="add_delete_toolbar" />
<button id="delete"> Delete</button>
How can I fill this jquery function according to my need:
$('button#delete').click(function () {
...
});
Checking which row is selecting :
$(document).ready(function () {
var table = $('#result').DataTable();
$('#result tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
}
Thanks a lot.
jQuery DataTable has a plugin called "TableTools" which provides many useful functionalities (including multi-select) and I suggest you to have a look. But to answer your question, try this in you code:
$('button#delete').click(function () {
$("#result tbody tr.selected").each(function() {
$.ajax({
type:"GET",
url: "ToYourController/Delete/" + this.id
})
.success(function() {
alert("succeed!")
})
.error(function() {
alert("failed!");
})
})
}
I have a list of checkboxes. Upon clicking on each of the checkboxes i am adding the value to the hidden variable. But the question is if I want to remove the value from the list upon unchecking the checkbox . How this piece cab be done
here is the hidden form variable
<input name="IDList[]" type="hidden" id="IDList" value="" />
and the jquery
$(".myCheckboxClass").change(function() {
var output = 0;
$(".myCheckboxClass").change(function() {
if ($(this).is(":checked")) {
output += ", " + $(this).val();
} else {
output = $.grep(output, function(value) {
return value != $(this).val();
});
}
$("#IDList").val(output);
});
});
Something like this: (demo) http://jsfiddle.net/wesbos/5N2kb/1/
we use an object called vals to store the info. ADding and removing as we check/uncheck.
var vals = {};
$('input[type=checkbox]').click(function() {
var that = $(this);
if (that.is(':checked')) {
console.log(this.name);
vals[this.name] = "In your Object";
}
else {
delete vals[this.name];
}
console.log(vals);
});
Following your logic, you could do this:
$('#IDList').data('value', []);
$(".myCheckboxClass").change(function() {
var list = $('#IDList').data('value');
if ($(this).is(":checked")) {
list.push($(this).val());
} else {
var indexToRemove = list.indexOf($(this).val());
list.splice(indexToRemove, 1);
}
$('#IDList').val(list);
});
But if you only care about the value of #IDList upon data submission or other actions, you probably want to consider an alternative approach: collating the checked values when you need them.
$('#form').submit(function() {
var list = $('input.myCheckboxClass:checked', this).map(function() {
return $(this).val();
}).get();
$('#IDList').val(list);
});
See both of the above in action: http://jsfiddle.net/william/F6gVg/1/.