I am creating a dynamic list of tasks that appear after the input is written and input's length is less or equal 30 characters and the button is pressed.
Together with the task there is a trash icon created.
I want to enable the user to remove chosen task when he clicks on the icon which comes from the external library ionicons.
I have an issue that when the trash icon is clicked, it removes this Li and all Li elements that were created after that clicked Li.
I am prepending li elements to the list.
Here's the snippet:
$('#addNewTaskBtn').click(function () {
var inputText = $('#dayTask').val();
var trashIcon = '<i class="ion-trash-b"></i>';
var newTask = $('<li />', { html: inputText + " " + trashIcon });
// clearing the input after click
$('#dayTask').val('');
if (inputText.length && inputText.length <= 30)
$(newTask).prependTo('ul.dayList');
$('.ion-trash-b').click(function () {
$(newTask).remove();
});
});
My question is:
How to remove only the one Li element which trash icon is clicked, and not all Li element (including the one) that were created later?
Thank you very much for your help.
$('.ion-trash-b').click(function(){
$(this).parent().remove(); // or $(this).closest("li").remove();
});
or even assign it onload to attach to all future trash icons using event delegation
$(function() {
$("#listContainer").on("click",".ion-trash-b",function(){
$(this).parent().remove();// or $(this).closest("li").remove();
});
});
where listContainer is the ID of the UL
Remove the closest li of the clicked ion-trash-b and as your elements are dynamically generated, use event delegation for ion-trash-b click event like following.
$('#addNewTaskBtn').click(function () {
var inputText = $('#dayTask').val();
var trashIcon = '<i class="ion-trash-b"></i>';
var newTask = $('<li />', { html: inputText + " " + trashIcon });
// clearing the input after click
$('#dayTask').val('');
if (inputText.length && inputText.length <= 30)
$(newTask).prependTo('ul.dayList');
});
$('body').on('click', '.ion-trash-b', function () {
$(this).closest('li').remove();
});
Related
I have the code below:
$(document).ready(function(){
var counter = 0;
$("button").click(function() {
$('body').append("<button>generate new element "+(counter++)+"</button>")
});
});
JSFiddle
When you click duplicated button, it won't duplicate another button again besides the original button only works.
Why cannot listen this event to duplicated buttons?
EDITED:
//Click button event DELEGATION
$(document).on("click",".choice", function() {
var userChoice = $(this).attr("value");
//EXTERNAL SPAGUETTHI CODE
};
Need to grab "value" of this button when it's clicked.
You need delegation: catching the clicks on the parent but only those that were made on button elements. $("button") selects the existing buttons on the page, $(document) (you can replace document with your button container) will select the container and by using $(document).click("button", ...) you delegate the clicks on the buttons.
$(document).ready(function() {
var counter = 0;
$(document).click("button", function(e) {
var value = $(e.target).attr("data-value"); // or .data("value")
alert(value);
$('body').append("<button data-value=\"" + ++counter + "\">generate new element " + counter + "</button>")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-value="initial-button">generate new element</button>
Here are some other similar answers I posted:
Direct and delegated events
Delete dynamic elements
Function not working second time
I have a form with an HTML table that has a button (#addRows) that when clicked will clone the first table row and append it to the bottom of the table.
This table resides in a section of HTML with some other input fields that can also be cloned and appended onto the bottom of my form. When I am cloning the section I am changing all child element ID's to include a number that can be iterated dependent on how many times the user clones the section.
Example
<div id="someID"> ... </div>
<div id="someID2"> ... </div>
<div id="someID3"> ... </div>
I am doing this with JQuery like this
$(function() {
var $section = $("#facility_section_info").clone();
var $cloneID = 1;
$( ".addSection" ).click(function() {
var $sectionClone = $section.clone(true).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + $cloneID); });
$('#facility_section_info').append($sectionClone);
$cloneID++;
});
});
When I clone the section that holds the table I am also cloning the #addRows button which when clicked should append a table row to the table it is being clicked on. However if I clone my section and I click on my second `#addRows button it will clone my table row but it is appending to my first table and not the second.
Here is my addRows button and event handler
<input type="button" value="+" id="addRows" class="addRows"/>
$(function() {
var $componentTB = $("#component_tb"),
$firstTRCopy = $("#row0").clone();
$idVal = 1;
$(document).on('click', '.addRows', function(){
var copy = $firstTRCopy.clone(true);
var newId = 'row' +$idVal;
copy.attr('id', newId);
$idVal += 1;
copy.children('td').last().append("Remove");
$componentTB.append(copy);
});
});
My question is, when I clone my section of HTML that holds my table and #addButton how can I ensure that when the user clicks on the original button it will clone and append to that table or if I click the cloned button it will clone and append to the cloned table only?
If anything is unclear please let me know so I can try to better explain what I am trying to do, thanks.
Here is a JSFiddle demonstrating the problem I am having.
Because I truly love you BigRabbit, here is where I got to. You will see at least one useful fix here:
var $sectionClone = $section.clone(true);
$sectionClone.find("*[id]").andSelf().each(function () {
$(this).attr("id", $(this).attr("id") + $cloneID);
});
and a fix for an issue you did not report yet
$copy.children('td').last().append(' Remove');
using
$("#facility_section_info").on('click', '.remove', function (e) {
e.preventDefault();
$("#"+$(this).data("removeid")).remove();
});
FIDDLE
$(function () {
var $componentTB = $("#component_tb"),
$firstTRCopy = $("#row0").clone(),
$section = $("#facility_section_info>fieldset").clone(),
$cloneID = 0,
$idVal = 0;
$("#facility_section_info").on('click', '.remove', function (e) {
e.preventDefault();
$("#"+$(this).data("removeid")).remove();
});
$("#facility_section_info").on('click', '.addRows', function () {
$idVal++;
var $copy = $firstTRCopy.clone(true);
var newId = 'row' + $idVal;
$copy.attr('id', newId);
$copy.children('td').last().append(' Remove');
$(this).closest("fieldset").find("tbody").append($copy);
});
$("#facility_section_info").on("click", ".addSection", function () {
$cloneID++;
var $sectionClone = $section.clone(true);
$sectionClone.find("*[id]").andSelf().each(function () {
$(this).attr("id", $(this).attr("id") + $cloneID);
});
$('#facility_section_info').append($sectionClone);
});
});
This is my jsfiddle
http://jsfiddle.net/1ty1v8u1/5/
If an element is clicked on twice , how can i achieve toggle behavior for that particular div ?
If i click on office twice in the jsfiddle how to make it open and close ??
This is my code
function showRestaurantDetailsByLocation(response,locationname)
{
$('.restListings').remove();
$('.addNewRestaurant').remove();
var ulhtml = $('<ul class="restListings"></ul>');
var divhtml = $('<div class="inner-intit"><sub class="sub">Your Favorite Area</sub></div>');
divhtml.append('<br>');
var $newbutton= $('<input/>').attr({ type: 'button', location:locationname , name:'btn1', class:'btn btn-success addNewRestaurant', value:locationname});
for(var i=0;i<response.length;i++)
{
divhtml.append('<li><h6>'+response[i].area+'</h6><p>'+response[i].address+'</p><span id="delete" class="inDelete inDeleteSub"></span></li>');
}
divhtml.append($newbutton);
ulhtml.append(divhtml);
$("#"+locationname).append(ulhtml);
}
You are appending the new elements on click. Just check for previously appended element in same div. If it exist then simply remove it, if not then add new:
$(document).on('click', '.lielement', function() {
var locationname = $(this).attr("id");
if($(this).find('.restListings').length)
$(this).find('.restListings').remove()
else
displayingRestaurantByArea(locationname);
});
Working Demo
I am using appendTo to move list items between two list, upon a button click. The button resides in each li element. Each li has two buttons, of which only one is visible at a time, depending on the list the li currently resides.
Here is the function:
// 'this' is the first list
// Click Handler for remove and add buttons
$(this.selector + ', ' + settings.target + ' li button').click(function(e) {
var button = $(e.target);
var listItem = button.parent('li');
listItem.children("button").toggleClass("hidden");
if (button.hasClass("assign")) {
// Add Element to assignment list
listItem.appendTo(settings.target);
}
else
if (button.hasClass("remove")) {
// Remove Element from assignment list
listItem.appendTo(source);
}
})
As long as the list item reside in the original li, the click events in the buttons are triggered. However, once it is moved to the other list using listItem.apendTo. The click item no longer fires. Why is this the case? I cant find anything about this in the docs.
Sometimes jQuery won't be able to find something if it isn't present in the DOM when your script first loads. If it is a dynamically created element, try replacing your click event handlers with 'on'
Rather than:
$(".aClass").click(function(){
// Code here
})
Try:
$("body").on("click", ".aClass", function(){
Code here
})
http://api.jquery.com/on/
You should use on event.
$(".aClass").on("click", function(){
//Your custom code
})
on event is usful for Dynamically generated data + static data already in HTML.
As recommended by user 'apsdehal', a deleate was what i needed:
// Click Handler for remove and add buttons
$(source.selector + ', ' + settings.target ).delegate("li button", "click", function(e) {
var button = $(e.target);
var listItem = button.parent('li');
listItem.children("button").toggleClass("hidden");
if (button.hasClass("assign")) {
// Add Element to assignment list
listItem.appendTo(settings.target);
}
else
if (button.hasClass("remove")) {
// Remove Element from assignment list
listItem.appendTo(source);
}
});
Something wrong with the event handler, as on mouse leave the div opens and closes 3 times.
also the radio that is swapped get over layed or offset.
I have tried everything, i think it has something to do with the way i am using the event.preventDefault();
UPDATE__
Menu opening 3x fixed, but the swapped radio in the div still overlaps any ideas?
http://www.apecharmony.co.uk
// RADIO BUTTON
$("input[name='domain_ext']").each(function () {
$("#domaindropradio1").attr('checked', 'checked');
var lbl = $(this).parent("label").text();
if ($(this).prop('checked')) {
$(this).hide();
$(this).after("<div class='radioButtonOn'>" + lbl + "</div>");
} else {
$(this).hide();
$(this).after("<div class='radioButtonOff'>" + lbl + "</div>");
}
});
$("input[type=radio]").change(function () {
$(this).siblings('.radioButtonOff').add('.radioButtonOn').toggleClass('radioButtonOff radioButtonOn');
});
// RIBBON RADIO DROPBOX
$('div.ribbonBoxarrow').click(function () {
$('.ribbonBoxarrow li').show('medium');
});
$('.ribbonBoxarrow li').mouseleave(function () {
$(this).hide('slow');
});
$("input[name='domain_ext']").parent('label').click(function () {
$('.ribbonBoxarrow li').hide('slow');
event.preventDefault();
});
//SWAP SECECTED RADIO
$("div.radiogroup2").on("click", ":radio", function () {
var l = $(this).closest('label');
var r = $('#radioselected');
r.removeAttr('id');
l.before(r.closest('label'));
$(this).attr('id', 'radioselected');
l.prependTo('.radiogroup1');
});
In response to:
the div opens and closes 3 times.
Your animations are triggering more events than you'd like. Also, your preventDefault() isn't preventing other click events from firing.
For your $("input[name='domain_ext']").parent('label') click event, try this:
$("input[name='domain_ext']").parent('label').click(function () {
$('.ribbonBoxarrow li').mouseleave();
event.stopImmediatePropagation();
});
For your second issue:
also the radio that is swapped get over layed or offset.
It looks like you're prepending radio buttons to an element with the radiogroup1 class, but you may want your radio buttons to be within the nested table element.
Solved, using tables to hold elements is what was causing the problem. If it is required then you would have to target the cell for swap.