I Follow This Article for Impalement CRUD Operation with HTML5 and Javascript.
So that Submit Data to Local Storage and save it.
my problem is Delete and Edit Operation when clicking on delete and edit button Nothing happens.
Javascript
$(function () {
var operation = "A";
var selected_index = -1;
var tbClients = localStorage.getItem("tbClients"); //Retrieve the stored data
tbClients = JSON.parse(tbClients); //Converts string to object
if (tbClients === null) //If there is no data, initialize an empty array
tbClients = [];
function Add() {
debugger;
var Data = {
ExternalProjects: {
Name: $('#Name').val(),
Body: $('#Body').val(),
Url: $('#Url').val()
}
};
tbClients.push(Data);
localStorage.setItem("tbClients", JSON.stringify(tbClients));
alert("The data was saved.");
List();
return true;
}
function Edit() {
tbClients[selected_index] = JSON.stringify({
Name: $('#Name').val(),
Body: $('#Body').val(),
Url: $('#Url').val()
}); //Alter the selected item on the table
localStorage.setItem("tbClients", JSON.stringify(tbClients));
operation = "A"; //Return to default value
return true;
}
function List() {
debugger;
var div = $('div#ExProjectList');
div.html("");
var cli = tbClients;
for (var i = 0; i < cli.length; i++) {
debugger;
div.append(
'<div href="#" class="list-group-item list-group-item-action flex-column align-items-start">' +
'<div class="d-flex w-100 justify-content-between">' +
' <h5 class="mb-1">' + cli[i].ExternalProjects.Name + '</h5>' +
' <small>' +
'<a id="btnDelete" alt="Delete' + i + '"><i class="fa fa-trash" style="cursor: pointer" ></i></a>' +
'<a id="btnEdit" alt="Edite' + i + '"><i class="fa fa-pencil" style="cursor: pointer"></i></a>'
+ '</small>' +
' </div>' +
'<p class="mb-1">' + cli[i].ExternalProjects.Body + '</p>' +
'<small>' + cli[i].ExternalProjects.Url + '</small>' +
'</div>'
);
}
}
function Delete() {
tbClients.splice(selected_index, 1);
localStorage.setItem("tbClients", JSON.stringify(tbClients));
}
$('#btnDelete').bind('click', function() {
selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
Delete();
List();
});
$("#btnEdit").bind("click", function() {
operation = "E";
selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
var cli = JSON.parse(tbClients[selected_index]);
$("#Name").val(cli.ExternalProjects.Name);
$("#Body").val(cli.ExternalProjects.Body);
$("#Url").val(cli.ExternalProjects.Url);
});
$("#AddExternalProject").click(function () {
if (operation === "A"){
return Add();
}
else{
return Edit();
}
});
});
You are creating the HTML dynamically, but not attaching the event to the element.
Instead of using:
$('#btnDelete').bind('click', function() {
selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
Delete();
List();
});
$("#btnEdit").bind("click", function() {
operation = "E";
selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
var cli = JSON.parse(tbClients[selected_index]);
$("#Name").val(cli.ExternalProjects.Name);
$("#Body").val(cli.ExternalProjects.Body);
$("#Url").val(cli.ExternalProjects.Url);
});
Use event delegation:
$("#ExProjectList").on("click", "#btnDelete", function() {
selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
Delete();
List();
});
$("#ExProjectList").on("click", "#btnEdit", function() {
operation = "E";
selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
var cli = JSON.parse(tbClients[selected_index]);
$("#Name").val(cli.ExternalProjects.Name);
$("#Body").val(cli.ExternalProjects.Body);
$("#Url").val(cli.ExternalProjects.Url);
});
If you are binding any event to any html element, always bind inside
$(document).ready(function(){
//code here
});
Because if you add the script earlier before Dom Content is ready, in self calling function then those elements will not be available to bind the events.
Related
When I edit panels name I want to update div content, that will have tab-pane name.
I tried to get the value and change it "onchange", but
I think I did something incorrectly.
http://jsfiddle.net/agata666/5zLmtqby/139/
var $foo = $(".tab-pane");
var $newPanelDefault = $foo.clone();
var hash = 1;
$(".add").on("click", function() {
var $newPanel = $newPanelDefault.clone();
var hashClass = 'zone-panel-' + generateHash();
$newPanel.find(".panel").data('hash', hashClass).attr("href", "#" + (++hash)).text("Zone " + hash);
$newPanel.attr("id", "tab" + hashClass);
var nextTab = $('.tabs li').size()+1;
$('<li class="' + hashClass + '">Zone ' + hash + ' <i class="fas fa-pencil-alt pencil"></i></li>').appendTo('.tabs');
$($newPanel).appendTo('.tab-content');
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
});
var panelDefault = document.querySelectorAll('.panel-default');
var exTabFirst = document.querySelectorAll('.exTabFirst');
var exTabSecond = document.querySelectorAll('.exTabSecond');
var addZoneButton = document.getElementById('add');
function generateHash() {
return Math.random().toString(16).substr(-5);
}
addZoneButton.addEventListener('click', function () {
var randomNumber = generateHash();
panelDefault.innerHTML = 'panel panel-default foo template ' + randomNumber;
exTabFirst.innerHTML = 'exTabFirst ' + randomNumber;
exTabSecond.innerHTML = 'exTabSecond ' + randomNumber;
});
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
Could you help me?
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;
});
var name, logo, streaming,twitchfeed;
var users = ["freecodecamp", "medrybw", "geoffstorbeck",
"terakilobyte", "habathcx", "robotCaleb",
"thomasballinger", "noobs2ninjas", "beohoff","boonyzarc"
];
function getInfo(){
users.forEach(function(user) {
var channelURL = 'https://api.twitch.tv/kraken/channels/' + user + '?callback=?';
var streamURL = 'https://api.twitch.tv/kraken/streams/' + user + '?callback=?';
$.getJSON(channelURL, function(channel) {
$.getJSON(streamURL, function(stream) {
if (stream.stream === null) {
streaming = '<span class="label label-danger pull-right label-rawle offline"><span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span></span>';
} else {
streaming = '<span class="label label-success pull-right label-rawle online"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span></span>';
}
twitchfeed = channel.url;
console.log(twitchfeed);
name = channel.display_name;
if (channel.logo === null) {
channel.logo = 'https://c1.staticflickr.com/1/186/382004453_f4b2772254.jpg';
}
logo = '<img src="' + channel.logo + '" class="logo">';
$('#person').append('<div class="user" id="' + name + '">');
$('#' + name).append(logo + '' + '<span class="name">' + name + '</span>' + '' + '</div>' + streaming);
$('#' + name).append('<div class="topic">' + stream.stream.channel.status + '</div>');
});
// what happens when tabs are clicked
$(function() {
// 'all' tab
$('#all').click(function() {
$('#all').addClass('active');
$('#online').removeClass('active');
$('#offline').removeClass('active');
$(".user").show();
});
});
// 'online' tab
$('#online').click(function() {
$('#all').removeClass('active');
$('#online').addClass('active');
$('#offline').removeClass('active');
$(".user").each(function() {
if ($(this).children(".offline").length < 1) {
$(this).show();
} else {
$(this).hide();
}
});
});
// 'offline' tab
$('#offline').click(function() {
$('#all').removeClass('active');
$('#online').removeClass('active');
$('#offline').addClass('active');
$(".user").each(function() {
if ($(this).children(".offline").length < 1) {
$(this).hide();
} else {
$(this).show();
}
});
});
});
});
}
//Trying to add a user
/*$('#submit-rawle-button').click(function(){
var $newUser = $('#newUser').val();
if(users.indexOf($newUser)==-1)
{
users.push($newUser);
}
getInfo();
});*/
getInfo();
I'm new to using JSON and the jquery $.getJSON function. If I pull all of the code out of the getInfo function and just call it once I have no problem. But maybe it's my lack of understanding but I thought if I put all that into a function. Then later I could add a button that after adding a new user to the user array. I could call the getInfo function again and it would give me a new JSON object updated with the new user that was added. However, instead I just get back empty objects. Will someone explain to me either why getInfo can't be called more than once or what my coding error is to not be getting updating JSON object.
The users.forEach is not waiting for the ajax calls to finish.I think the term is AJAX is asynchronous and the forEach is synchronous.
Keep this in mind every time you use ajax. I changed the code a bit so that it won't try to go to the next user UNTIL the second getJSON has finished.
There has to be a more elegant way to do this. I also recommend looking in to promises it will come in handy in the future. Hope this helps.
var name, logo, streaming, twitchfeed;
var users = ["freecodecamp", "medrybw", "geoffstorbeck",
"terakilobyte", "habathcx", "robotCaleb",
"thomasballinger", "noobs2ninjas", "beohoff", "boonyzarc"
];
function getInfo() {
var usersTotal = users.length;
var userCounter = 0;
function getNextUser() {
if (usersTotal > userCounter) {
var user = users[userCounter];
var channelURL = 'https://api.twitch.tv/kraken/channels/' + user + '?callback=?';
var streamURL = 'https://api.twitch.tv/kraken/streams/' + user + '?callback=?';
$.getJSON(channelURL, function (channel) {
$.getJSON(streamURL, function (stream) {
if (stream.stream === null) {
streaming = '<span class="label label-danger pull-right label-rawle offline"><span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span></span>';
} else {
streaming = '<span class="label label-success pull-right label-rawle online"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span></span>';
}
twitchfeed = channel.url;
console.log(twitchfeed);
name = channel.display_name;
if (channel.logo === null) {
channel.logo = 'https://c1.staticflickr.com/1/186/382004453_f4b2772254.jpg';
}
logo = '<img src="' + channel.logo + '" class="logo">';
$('#person').append('<div class="user" id="' + name + '">');
$('#' + name).append(logo + '' + '<span class="name">' + name + '</span>' + '' + '</div>' + streaming);
$('#' + name).append('<div class="topic">' + stream.stream.channel.status + '</div>');
});
// what happens when tabs are clicked
$(function () {
// 'all' tab
$('#all').click(function () {
$('#all').addClass('active');
$('#online').removeClass('active');
$('#offline').removeClass('active');
$(".user").show();
});
});
// 'online' tab
$('#online').click(function () {
$('#all').removeClass('active');
$('#online').addClass('active');
$('#offline').removeClass('active');
$(".user").each(function () {
if ($(this).children(".offline").length < 1) {
$(this).show();
} else {
$(this).hide();
}
});
});
// 'offline' tab
$('#offline').click(function () {
$('#all').removeClass('active');
$('#online').removeClass('active');
$('#offline').addClass('active');
$(".user").each(function () {
if ($(this).children(".offline").length < 1) {
$(this).hide();
} else {
$(this).show();
}
});
});
});
}
userCounter++;
getNextUser();
}
getNextUser();
}
//Trying to add a user
/*$('#submit-rawle-button').click(function(){
var $newUser = $('#newUser').val();
if(users.indexOf($newUser)==-1)
{
users.push($newUser);
}
getInfo();
});*/
getInfo();
Buildgames returns rows:
<a>....</a>
<a>....</a>
When I click on each a the Buildcar_s function returns all the data inside an alert.
Instead of this alert I want to put all the results in a div under each a, so it would look like:
<a>.....clicked ...</a>
<div>....
...
</div>
<a>....not clicked...</a>
<a>....not clicked...</a>
<a>....not clicked...</a>
How can we put a div only under the a which was clicked?
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += 'mmmmmm<br/>';
});
place += '</div>';
return place;
}
Try this, relevant changes have been commented:
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
var $a = this;
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
// this inserts the HTML generated from the function,
// under the A element which was clicked on.
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += '<div style="float: right;"> ' + this.CITY + ' ' + '</div><BR />' + +'<br/><br/>';
});
place += '</div>';
return place; // returns the string created, as opposed to alerting it.
}