I have a "todo" application that I've added a delete button to. The application is already set up to post via an ajax request, but the delete button causes a page re-load after it is clicked. I feel like preventDefault should... well prevent that from happening, but it doesn't. Any advice would be much appreciated!
function to list tasks
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id + '" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' + " data-id='" +
task.id + "'" + checkedStatus + ' /><label>' + task.title +
'</label><a class="destroy" rel="nofollow" data-method="delete" href="/tasks/' + task.id +
'"></a></div></li>';
return liElement;
}
delete task function
function deleteTask(e) {
e.preventDefault();
var itemId = $(e.target).data("id");
$.ajax("/tasks/" + itemId, {
_method: "DELETE",
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith('');
});
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
$('.destroy').click(deleteTask);
});
Remove the href from the <a> tag. I will recommend to change this to a <button> since you are not taking the user to any other page.
I also suspect this will not work:
var itemId = $(e.target).data("id");
Try changing it to:
var itemId = $(this).parent().data("id");
Related
I have Using Nestable js to drag and drop my list items .and the drag and drop is working fine in UI .but what i need is ,I want to update the status of list items after the item is dropped..How can i achieve this using javascript..
for reference of Nestable js https://codepen.io/Mestika/pen/vNpvVw
Next am retrieving the list items like bellow code
var ListEnumerator = this.myItems.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
var status = currentItem.get_item('Status');
if (status == "Planned") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridprocess').append(templateString);
}
else if (status == "In Process") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridinprogress').append(templateString);
}
else if (status == "Completed") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridcomplete').append(templateString);
}
else if (status == "Hold") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridincomplete').append(templateString);
}
}
here the li tag is used under
<div class="dd">
<ol class="dd-list" id="gridprocess" >
</ol>
</div>
how can i update the status while drag and drop? please give the code to do it..
Finally I achieved the above question . with the following code...... first i have set on ID to the class name dd as ddprocess like bellow
<div class="dd" id="ddprocess">
<ol class="dd-list" id="gridprocess">
</ol>
</div>
And Next I have Write a function When the id ddprocess is on change i get the Each item id and pass the ID to the Update function
$('#ddprocess').on('change', function () {
// JSON To get the list item in Process
var $this = $(this);
var serializedData = window.JSON.stringify($($this).nestable('serialize'));
// console.log("sData:", serializedData)
// convert the JSON into Object
var obj = JSON.parse(serializedData);
obj.forEach(myFunction);
function myFunction(item, index) {
var eachid = item.id;
// console.log("Item-id", eachid);//you will get id
Updatetoprocess(eachid);
}
});
Next the update function is to Update the status to planned for each item in the ddprocess id .....
function Updatetoprocess(eachid) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
var siteurl = "https://abb.sharepoint.com/sites/IAPI-SOP";
var context = new SP.ClientContext(siteurl);
var olistnew = context.get_web().get_lists().getByTitle("TaskList");
var listitem = olistnew.getItemById(eachid);
listitem.set_item('Status', 'Planned');
listitem.update();
context.load(listitem);
context.executeQueryAsync(function () {
alert("Items Updated successfully");
},
function () { console.log("failure") }
)
});
}
Thank you
I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.
I'm trying use this function to prevent the duplicate but only work for prevent not to break action. How to make this function work not only for prevent but for break action too ?
function AddTipeTruk() {
var form = $("#formtruk");
var contents = {},
duplicates = false;
$("#table-custtiptruk td").each(function () {
var tdContent = $(this).text();
if (contents[tdContent]) {
duplicates = true;
return false;
}
contents[tdContent] = true;
});
if (duplicates) {
alert("There were duplicates.");
}
if (form.valid()) {
var markup = "";
markup = "<tr><input id='TipTrukId' name='TipTrukId' type='hidden' value='1'><td style='display:none;'><input value='" + 1 + ";" +
+$('#JenisTruck option:selected').val() + ";" + $('#Alias').val() + ";" +
"' name='TipTrukData'/> </td><td class='no'></td><td>" + $('#JenisTruck option:selected').text() + "</td><td>" + $('#Alias').val() + "</td>" +
"<td><a href='#' data-toggle='modal' onclick='EditTipTrukRow($(this))'>Edit</a> | <a href='#' onclick='RemoveTipTrukRow($(this));'>Delete</a></td></tr>";
$("#table-custtiptruk tbody").append(markup);
updateRowNumberTipTruk();
$('#modal').modal('hide');
}
}
You are jumping from inner loop. You need to jump from function too.
See below.
$("#table-custtiptruk td").each(function () {
var tdContent = $(this).text();
if (contents[tdContent]) {
duplicates = true;
return false;
}
if(duplicates ==true){
return !duplicates;
}
contents[tdContent] = true;
});
I am not able to create an edit in place feature with JavaScript/ jQuery. I could not use the plugin editinplace, because I need to put a datepicker on it. My code below does not work for some strange reason:
function editImpfDatumImpfung1Clicked(sender)
{
var sText = $(this).text();
var sId = $(this).attr("id");
$(this).attr("id", "tobechanged");
$(this).after('<input type="text" id="' + sId + '" value="' + sText + '" />');
$(this).remove();
bImpfung1Clicked = true;
$("#" + sId).focus();
$("#" + sId).datepicker(datepickerOptions);
if (bFirstRegisterImpfung1 === true)
{
firstRegisterImpfung1();
bFirstRegisterImpfung1 = false;
}
}
$(document).ready(function()
{
$elem = $("span[id^='impfung_1['");
if ($elem.length > 0)
{
bFirstRegisterImpfung1 = true;
$elem.click(editImpfDatumImpfung1Clicked);
}
});
Edit:
No Errors in console.
console.log($("#" + sId).val()); causes undefined
Edit 2:
Just needed to escape the id like this:
sId = sId.replace(/[[]/g,'\\[');
sId = "#" + sId.replace(/]/g,'\\]');
Thanks for your advice.
I imagine you have a typo in the following line:
$elem = $("span[id^='impfung_1['");
try this instead:
$elem = $("span[id^='impfung_1']");
I'm doing the following:
$('.document-content').on('input', function() {
var headers;
headers = $('.document-content > h2').each(function() {
var headerId, headerText;
headerId = $(this).attr('id');
headerText = $(this).text();
$('.document-outline').empty().append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
});
});
In order to avoid duplication, I added empty() but now only the last item in the each loop is being appended to .document-outline.
How can I fix this?
You need to empty it before the loop, else before adding any item you are removing the previous contents meaning all the previous items are removed thus only the last item in the loop is kept
$('.document-content').on('input', function () {
var $ct = $('.document-outline').empty();
var headers;
headers = $('.document-content > h2').each(function () {
var headerId, headerText;
headerId = $(this).attr('id');
headerText = $(this).text();
$ct.append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
});
});
You need to empty() the containing element outside of the loop, otherwise it is being cleared on each iteration.
$('.document-content').on('input', function() {
var $headers = $('.document-content > h2'),
$outline = $('.document-outline').empty()
$headers.each(function() {
var headerId = $(this).attr('id'),
headerText = $(this).text();
$outline.append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
});
});
Note that I shortened the logic slightly by setting the values as the variables are declared.
Empty it outside loop otherwise you will end with appending last elements only as everything before it will get emptied
$('.document-content').on('input', function() {
var headers,
var outlineDoc = $('.document-outline').empty()
headers = $('.document-content > h2').each(function() {
var headerId, headerText;
headerId = $(this).attr('id');
headerText = $(this).text();
$(outlineDoc).append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
});
});