Button to remove a dynamically created list element using JQuery - javascript

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();
}

Related

"Add to Favorite / Remove" - Ajax not working

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');

remove single li using localStorage jQuery

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
});

Assign click-event on a new element in the event itself

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);
}
});

trying to append content to DOM element

I'm trying to add a div to a row of content with the click of a button. My code works for the first row but not for any other row. Please help. This is the function for the button:
$(".addMMbtn").each(function() {
$(this).bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
});
You can see a fiddle of the problem here: http://jsfiddle.net/z7uuJ/
$(".addMMbtn") will only find the elements present on the page and your code will only attach click event handler on them. Since you are adding the elements dynamically you should either use delegate or on (if you are using jQuery 1.7+) for click event to work on them too. Try this
Using delegate
$('#default').delegate('.addMMbtn', 'click', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
Using on
$('#default').on('click', '.addMMbtn', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
Demo
Instead of assigning click event directly on the button you need to use on():
$(document).on("click", ".addMMbtn",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
In this case event handler will be subscribed to all newly added elements.
Code: http://jsfiddle.net/z7uuJ/5/
You don't need to loop through the elements to bind the handler:
$(".addMMbtn").live('click', function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
});

How to hide a dom element after creating it on the fly with JQuery?

I am trying to build a form where users can add a text field by clicking on a "add option" button. They can also remove added fields by a "remove option" link created on the fly by Jquery, along with the text field.
JavaScript:
$(document).ready(function(){
$("#add_option").click(function()
{
var form = $("form");
var input_field = '<input type="text" />';
var delete_link = 'remove';
form.append(input_field + delete_link);
return false;
});
$("a").click(function()
{
alert('clicked');
return false;
});
});
When I click on the "add_option" button, a new text field and the "delete_link" appear. But when clicking on the "delete_link" created by JQuery, the browser follows the link instead of launching a pop-up displaying "clicked".
How do I hide a dom element after creating it on the fly with JQuery?
I'd use delegate because its uses less bubbling :
$(document).delegate("a", "click", function(){
alert('clicked');
});
EDIT , here is your code you need to change :
$(document).ready(function(){
$("#add_option").click(function(){
var form = $("form");
var input_field = '<input type="text" />';
input_field.addClass = "dynamic-texfield";
var delete_link = 'remove';
form.append(input_field + delete_link);
return false;
});
Then comes the delegate part :
$(document).delegate(".delete-trigger", "click", function(){
alert('ready to delete textfield with class' + $(".dynamic-texfield").attr("class"));
});
Try binding the handler for the <a> with "live"
$('a').live('click', function() { alert("clicked); });
You probably should qualify those <a> links with a class or something.
I don't get why you're using a <a> as a button to execute a function in jQuery. You have all the tools you need right in the framework to totally bypass well-worn traditions of HTML.
Just put a css cursor:pointer definition on the button you want to appear "clickable," add some text-decoration if that's your fancy, and then define your function with jQ:
$('.remove-button').live('click', function() {
$(this).parent().remove();
}

Categories