can I get some help on finding a solution on how to remove a single li when using local storage? this is todo list type functionality.
i am able to select & remove "this" item, however, on page/browser refresh the entire ul removes.
what I am trying to do is have only the selected item(s) remove, even if the page/browser does refresh.
i believe the list[i] may be my issue, but what other way could i select $(this) from within localStorage?
<h1>simple todo</h1>
<form id="form">
<input type="text" placeholder="Add New...">
<button>Add Item</button>
</form>
<ul id="list"></ul>
<script>
//add
$("button").on("click", function() {
var $item = $("input").val();
$("ul").append("<li>" + $item + "</li>");
//set
$('#form')[0].reset();
var list = $('#list').html();
localStorage.setItem('list', list);
return false;
});
//show
if(localStorage.getItem('list')) {
$('#list').html(localStorage.getItem('list'));
}
//remove
$("ul").on("click", "li", function() {
$(this).css("color", "gray");
var i = $(this).val();
localStorage.removeItem(list[i]);
localStorage.clear();
});
</script>
Change your removing method like this
//remove
$("ul").on("click", "li", function () {
$(this).css("color", "gray");
var i = $(this).text();
var currentList = localStorage.getItem('list'); // get the current list as a string.
var newList = currentList.replace('<li>' + i + '</li>', ''); // replace the clicked item with a blank string. But if you have multiple tasks with the same name this will cause deleting the first occurrence of it.
localStorage.setItem('list', newList); // update the localStorage with the new list
});
Related
I want to create a "Add to favorite" & "Remove from favorite".
When I add the favorite, I change the ID of the DIV for remove.
I can successfully add to favorite but I can't undo.
This code for add
$('#addToFavoriteButton').click(function (event) {
var ItemID = $('#addToFavoriteButton').data('itemid');
event.preventDefault();
$.post('/system/ajax.php', {
AddFavID: ItemID
}, function (response) {
document['getElementById']('addToFavorite').id = 'RemoveFavoriteButton';
});
});
This code for remove
$('#RemoveFavoriteButton').click(function (event) {
var ItemID = $('#RemoveFavoriteButton').data('itemid');
event.preventDefault();
$.post('/system/ajax.php', {
RemoveFavbidID: ItemID
}, function (response) {
document['getElementById']('RemoveFavoriteButton').id = 'addToFavoriteButton';
});
});
Where am I wrong?
The main problem with your code is that you are assigning an event handler to a button and then changing the ID of that button, expecting it to trigger different code when it is clicked. That is wrong.
If you change the ID of an element it will still trigger the event handler that you originally assigned to it. See this example...
$("#button1").on("click", function() {
alert("you clicked button 1 - my id is " + this.id);
});
$("#button2").on("click", function() {
alert("you clicked button 2");
});
// change the ID of #button1 to #button2
$("#button1").attr("id", "button2");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button1">button 1</button><br/>
<button id="button2">button 2</button><br/>
What makes more sense is to have a button to add a favourite, and a button to remove a favourite. You just hide the remove button until add is clicked, and vice-versa.
Like this...
var $add = $("#addFavourite");
var $remove = $("#removeFavourite");
$add.on("click", function() {
$add.hide();
$remove.show();
var itemId = $add.data("item-id");
alert("adding item " + itemId);
// do your AJAX stuff to add the favourite here
});
$remove.on("click", function() {
$add.show();
$remove.hide();
var itemId = $add.data("item-id");
alert("removing item " + itemId);
// do your AJAX stuff to remove the favourite here
});
#removeFavourite {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="addFavourite" data-item-id="123">add favourite</button>
<button id="removeFavourite" data-item-id="123">remove favourite</button>
I Suggested that you change the class instead of the id, since the id must be unique.
Or you can always use HTML5 data attribute, which you can use for both CSS styling (using attribute selector) and JS use (with dataset or jQuery's .data () method). see
Example:
HTML
<div id="el" data-test="data"></div>
vanilla javascript
var el = document.getElementById('el');
el.dataset.test // 'data'
by the way how you get the id is wrong -
document['getElementById']('RemoveFavoriteButton').id
You must use
vanilla javascript
document.getElementById('RemoveFavoriteButton').id;
jQuery
$('#RemoveFavoriteButton')attr('id');
I have an ordered list in HTML:
<ol id ="list">
</ol>
which gets added to using JQuery/javascript:
$(function (){
$("#click-me").click(function (e){
e.preventDefault();
i++;
var list = $("#list");
var name = $("#colleague-select option:selected").text();
var remove = "<button type='button' class='remove-me'> X </button>";
var entry = "<li>" + name + remove+ "</li>";
entry.id = "entryid" + i;
list.append(entry);
return false;
});
});
What I'm trying to do is to allow a user to remove an entry in the list by clicking its corresponding button "X". This is the code I've come up with, but it's not working:
$(function (){
$(".remove-me").click(function(e){
var list = $("#list");
var entry = e.parent(); //find parent entry of clicked "X" button
list.remove(entry); //remove entry from list
});
});
Any help guys? I am fairly new to JQuery so an explanation of your answer code would be much appreciated. Thanks.
You need to use event delegation for binding events to dynamically added elements.
$(document).on('click', ".remove-me", function(e){
var entry = $(this).parent();
entry.remove(); //remove entry from list
});
just remove the parent element
$(function (){
$(document).on("click", ".remove-me", function(e){
$(this).parent().remove(); //find parent entry of clicked "X" button
});
});
A foolproof way is add the event to the button
<button type='button' onclick='removeMe(this);' class='remove-me'> X </button>
and on js
function removeMe(e)
{
$(e).parent().remove();
}
I want to create a new element and assign this element the same event for onclick, which it has created it.
DEMO
$(function(){
var counter = 0;
$('.sub').click(function(event){
event.stopPropagation();
counter++;
$div = $(this); // makes more sense in the original code
$div.append('<div class="sub" title="subsub">subsub' + counter + '</div>');
//$div.find('.sub').click // <-- ?????
});
});
In my demo I want to create a new subsub for every sub, which was clicked. Than I want to add the same click event to the new subsub element.
Could anyone help me with this?
I've found nothing for this problem. Maybe I don't have the correct keywords for google or SO :/
Just use event Delegation
$(document).on('click', '.sub', function(event){
Your click events seem to be working correctly at this point,because you are using append which actually nests the new div inside the div that is clicked. Try using after and the functionality breaks.
$(function(){
var counter = 0;
$(document).on('click', '.sub', function(event){
event.stopPropagation();
counter++;
$div = $(this); // makes more sense in the original code
$div.after('<div class="sub" title="subsub">subsub' + counter + '</div>');
});
});
Check Fiddle
Why not create proper elements instead :
$(function(){
var counter = 0;
$('.sub').on('click', doStuff);
function doStuff(event) {
event.stopPropagation();
counter++;
var $div = $(this),
$sub = $('<div />', {'class':'sub',
title : 'subsub',
text : 'subsub' + counter,
on : {
click : doStuff
}
}
);
$div.append($sub);
}
});
i have a single filed which i need to clone with a clone button and remove button to remove the cloned filed only
i made this simple script but i believe it contain something wrong since its not working :)
HTML
<form method="post">
<div id="fileds">
<select name="lang" id='lang'>
<option>select language</option>
</select>
</div>
</form>
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
JS
$(function(){
var regex = /^(.*)(\d)+$/i;
var cloneIndex = $("#lang").length;
$("button.clone").live("click", function(){
$(this).parents("#lang").clone()
.appendTo(".fileds")
.attr("id", "lang" + cloneIndex)
.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
});
cloneIndex++;
});
});
also i didn't find how to write the remove code for the remove button
Thank you
1) The #lang is not a parent of .clone
2) .fields should be #field as this is and ID
This code should work. Live Demo
$(function() {
var counter = 1;
$(".clone").live("click", function() {
$("#lang:first").clone().appendTo("#fileds").addClass("lang" + counter);
counter++
});
$(".remove").live('click', function() {
if (counter > 1) { //Only apply if the lang field is more than 1
counter = counter - 1;
$("#lang:last").remove();
}
});
});
the lang is not parent of the buttons, i have added a class and a handler for remove button, try this:
$(function(){
$(".clone").on("click", function() { // you can use `on` instead of live which is deprecated
var cloneIndex = $(".lang").length; // you can find the the current length of `.lang` within the handler
$(".lang:last").clone() // clones the last element with class of `lang`
.attr("id", "lang" + cloneIndex)
.appendTo("#fileds") // change this to id selector
});
$("button.remove").on("click", function(){ // '.remove' click handler
$(".lang:last").remove()
})
});
DEMO
My current setup loads a dynamic list at which point I create a click event via jquery like so:
$('#listReports li').click(function () {
var selected = $(this).text();
alert("List Item: " + selected);
});
I have code that lets a user save a report which gets appended to the list. The new item in the list doesn't trigger the click event until I call the function again. The problem with this is for the older items the event is getting triggered twice.
Here is how I append my list items and call then function again:
$("#save").click(function (e) {
if ($("#reportParams li").size()> 0) {
var fileName = $('#reportFileName').val();
if (!fileName) {
alert("You must enter a file name!");
}
else {
$('#listReports').append('<li>'+fileName+'</li>');
$('#listReports li').click(function () {
var selected = $(this).text();
alert("List Item: " + selected);
});
}
}
});
Is there a way to define the click event only once and have it effect new items appended to the list?
Instead of .click(), use .live():
$('#listReports li').live('click', function ()
{
var selected = $(this).text();
alert("List Item: " + selected);
});
or .delegate():
$('#listReports').delegate('li', 'click', function ()
{
var selected = $(this).text();
alert("List Item: " + selected);
});