I have a simple list where you can add items in html/jquery.
I want to remove a specific item when i click on it in the list.
I can add items, they show up but the remove code is not working.
Remove code
$('#items a.delete').on('click', function(){
$(this).parent().remove();
});
This is my code:
$(document).on('pagebeforeshow', '#home', function(event) {
homepage();
});
$('#items a.delete').on('click', function(){
$(this).parent().remove();
});
function homepage(){
// Fetch the existing objects
objects = getObjects();
// Clear the list
$('#items').find('li').remove();
// Add every object to the objects list
$.each(objects, function(index, item){
element = '<li data-icon="delete">'+item.title+'</li>';
$('#items').append(element);
});
$('#items').listview();
$('#items').listview("refresh");
}
function getObjects(){
// See if objects is inside localStorage
if (localStorage.getItem("objects")){
// If yes, then load the objects
objects = JSON.parse(localStorage.getItem("objects"));
}else{
// Make a new array of objects
objects = new Array();
}
return objects;
}
homepage() gets called when you enter the page, it repopulates the list.
Objects are stored in localstorage.
HTML:
<ul id="items" data-role="listview" data-inset="true"></ul> <br>
You are binding the events before you are appending them to the DOM. When the elements are then appended, you'll need to bind the event after, or use event delegation to find that element. A possible fix would be to move this code block
$('#items a.delete').on('click', function(){
$(this).parent().remove();
});
after you call the homepage() function.
You are dynamically adding new elements, so you need to target the parent element on your event binding:
$('#items').on('click', 'a.delete', function(){
$(this).parent().remove();
});
Related
I am creating a To-Do list with the ability to remove specific items from the list. I am currently trying to use 'localStorage' to essentially save the list on page refresh. However, when I delete an item from the list, the 'localStorage' does not work as intended and instead removes the first item in the array when you next load the page.
JS & jQuery:
$(document).ready(function () {
$(document).on('click', '.delete-task', function () { // We use 'on' as the element is dynamically added
console.log("'Delete' button pressed");
var foo = $(this).closest('li');
console.log(foo);
$(this).closest('li').fadeOut(250, function() {
arr.splice(foo, 1);
$(this).remove(); // Dynamically remove the DOM element from the list
localStorage.setItem('items', JSON.stringify(arr));
console.log(arr);
console.log(localStorage.getItem('items'));
});
});
});
If interested, the HTML format of an item within the 'ul' list looks similar to this:
<li><span class="text-task">5</span><span class="delete-task">x</span></li>
I am expecting the selected item from the list to be removed and store within the localStorage correctly when you next load the page.
Update:
As #Slim pointed out, 'foo' is a JS object and not an index.
My question is, how do I find the index of the specified item (the 'li') within the 'arr' array?
You could try to find the parent of foo using .parent() ( https://api.jquery.com/parent/ ) and then find the index of given li by using .index() ( https://api.jquery.com/index/ )
...
var index = foo.parent().index( foo );
arr.splice(index, 1);
...
Also, you should try to cache jQuery object. Calling multiple times $(this) is calculating the same thing multiple times.
For example:
...
var $self = $(this)
var foo = $self.closest('li');
console.log(foo);
$self.closest('li').fadeOut(250, function() {
...
Also, good idea is to name variables containing jQuery objects starting with $ - it's quite a common pattern.
simulate this
<ul id="list">
<li data-id="1" >Coffee <span class="delete-task">x</span></li>
<li data-id="2" >Tea <span class="delete-task">x</span></li>
<li data-id="3" >Milk <span class="delete-task">x</span></li>
</ul>
use id value here
$(document).on('click', '.delete-task', function () {
var id = $(this).parents('li').attr('data-id');
for (var k in arr) {
if (typeof arr[k] !== 'function') {
if (arr[k].id == id) {
//your codes
break;
}
}
}
});
I also recommend you use : https://github.com/localForage/localForage
I have an unordered list and the li elements inside of it are rendered based on the number of items in an array in my backend.
As new items are added to an array, a corresponding li element is rendered and pops up in my list. Is it possible to give each new li element a slideDown() animation?
Yes, but you need to use .on() or .live() depending on which version of JQuery you're using.
http://api.jquery.com/on/
http://api.jquery.com/live/
Ok so try this wrap this in a function
function doSlideDown(){
$('ul > li > input[type="checkbox"]').on("click", function() {
var parent = $(this).parent("li");
if($(this).is(":checked") === true) {
// move to the top
$(parent).slideUp(300, function() {
$(parent).prependTo($(parent).parent());
$(parent).slideDown(300);
});
} else {
$(parent).slideUp(300, function() {
$(parent).appendTo($(parent).parent());
$(parent).slideDown(300);
});
}
});
}
then add this outside of your document ready function
$(document).ajaxComplete(function() {
doSlideDown();
});
That will update the DOM every time your run some ajax and append a new item.
I am working on a project in which I need to add the list items from list1 to list2 on dblclick of it or either pressing Add button.
So far I have accomplished this Working jsfiddle.
$().ready(function() {
var classHighlight = 'highlight';
var $thumbs = $('ul li').click(function(e) {
e.preventDefault();
$thumbs.removeClass(classHighlight);
$(this).addClass(classHighlight);
});
$('#select1').on ("dblclick","li", function(){
return $(this).appendTo('#select2').removeClass('highlight');
});
$('#select2').on ("dblclick","li", function(){
return $(this).remove();
});
$('#add').click(function() {
$('#select1 .highlight').appendTo('#select2').removeClass('highlight');
});
$('#remove').click(function() {
$('#select2 .highlight').remove();
});
});
But if you see clicking on the list1 item also removes the clicked item from list1 which I dont want to. I only need to copy it from list1 to list2 Can anyone help me with this?
Thank You
When you append an existing element to a new parent, you move it; it doesn't get copied. You should clone the element first and then append cloned element:
$('#select1').on ("dblclick","li", function(){
return $(this).clone().appendTo('#select2').removeClass('highlight');
});
and
$('#add').click(function() {
$('#select1 .highlight').clone().appendTo('#select2').removeClass('highlight');
});
Working Demo
you use clone() function to help in this code
$('#select1').on ("dblclick","li", function(){
return $(this).clone().appendTo('#select2').removeClass('highlight');
});
whole code here
http://jsfiddle.net/s41txkng/4/
https://api.jquery.com/clone/
I'll try to explain my problem:
I have a website where the user dynamically adds elements. They all belong to the "toBuy" class. Whenever a new element is added to this class I need to attach a click-handler to only this element but not to all others. To keep my code clean I want to have a function that does this work. Here is what i've tried:
this is how the stuff is added:
$("#addItemButton").click(function(){
var item= $('#item').val();
$('#item').val("");
var quantity= $('#quantity').val();
$('#quantity').val("");
var comment=$('#addComment').val();
$('#addComment').val("");
//construct new html
var newitem="<div class='toBuyItem'><div class='item'>";
newitem+=item;
newitem+="</div><div class='quantity'>";
newitem+=quantity;
newitem+="</div><div class='comment'><img src='img/comment";
if(comment==""){
newitem+="_none"
}
newitem+=".png' alt='Comment'></div><div class='itemComment'>"
newitem+=comment;
newitem+="</div></div>";
$("#toBuyItems" ).prepend( newitem );
toggle("#addItemClicked");
initializeEventListeners();
});
then this is the initializeEventListeners function (which I also run when the page loads so that the existing elements have the event handlers already:
function initializeEventListeners(){
$(".toBuyItem").click(function(){
console.log($(this).html());
console.log($(this).has('.itemComment').length);
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
}
function toggle(item){
$( item ).slideToggle(500);
}
now apparently what happens is that when a new element is added the existing elements get a new event handler for clicking (so they have it twice). Meaning that they toggle on and off with just one click. Probably it's damn simple but I cannot wrap my head around it....
EDIT:
so this works:
$(document).on('click', '.toBuyItem', function(){
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
Use jquery's on method. This way you have to add event only once. This will be added automatically to dynamically added elements.
$(document/parentSelector).on('click', '.toBuyItem', function() {
// Event handler code here
});
If you are using parentSelector in the above syntax, it has to be present at the time of adding event.
Docs: https://api.jquery.com/on
You can use jQuery.on method. It can attach handlers to all existing in the DOM and created in future tags of the selector. Syntax is as follows:
$(document).on('click', '.toBuyItem', function(){
//do onClick stuff
})
As others have suggested, you can delegate click handling to document or some suitable container element, and that's probably what I would do.
But you could alternatively define a named click handler, which would be available to be attached to elements already present on page load, and (scope permitting) to elements added later.
You might choose to write ...
function buy() {
if($(this).has('.itemComment').length != 0) {
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
}
function initializeEventListeners() {
$(".toBuyItem").on('click', buy);
}
$("#addItemButton").on('click', function() {
var item = $('#item').val(),
quantity = $('#quantity').val(),
comment = $('#addComment').val();
$('#item', '#quantity', '#addComment').val("");
//construct and append a new item
var $newitem = $('<div class="toBuyItem"><div class="item">' + item + '</div><div class="quantity">' + quantity + '</div><div class="comment"><img alt="Comment"></div><div class="itemComment">' + comment + '</div></div>').prependTo("#toBuyItems").on('click', buy);// <<<<< here, you benefit from having named the click handler
$newitem.find(".comment img").attr('src', comment ? 'img/comment.png' : 'img/comment_none.png');
toggle("#addItemClicked");
});
I have an HTML table and jQuery handlers to move rows up and down, using .next() and .prev(), but I also want to add new rows and after adding new row and trying to move old rows up or down they move more positions than expected. Here is an example on jsfiddle http://jsfiddle.net/3CQYN/
$(function() {
initControls();
$('.new').click(function() {
$('<tr><td>TEST</td><td>Up Down</td></tr>').appendTo($('table tbody'));
initControls();
});
});
function initControls()
{
$('.down').click(function() {
var parentRow = $(this).closest('tr');
parentRow.insertAfter(parentRow.next());
});
$('.up').click(function() {
var parentRow = $(this).closest('tr');
parentRow.insertBefore(parentRow.prev());
});
}
Try to move rows up and down, then add few new rows and move the OLD rows up and down again and you'll see the problem.
Every time you add a new row, you rebind the handlers, ending up with multiple handlers bound to individual up and down links. Instead, use event delegation (only executed once, on DOM ready):
$(document).on('click', '.down', function() {
// ...
});
$(document).on('click', '.up', function() {
// ...
});
http://jsfiddle.net/Gt4Zq/
Note that if you can find a container to bind to that is closer to the elements than document, that would be preferable.