Duplicated button doesn't work click(); - javascript

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

Related

on.click not working after first click on dynamically created table

I dynamically create a table full of links of 'actors', which allows to pull the actors information into a form to delete or update the row. The delete button only pops up when you select an actor.
I'm able to click a row, pull the information into the forms, and delete it on first try. However when I attempt to add a new 'Actor' and then delete it, or just delete an existing 2nd row, the button 'Delete Actor' doesn't work. It's only after the first successful delete does the button no longer work.
var addActor = function() {
// Creates a table of links for each added actor with an id based from # of actors
$("#actorsTable").append("<tr><td><a href='' onclick='deleteActor(this)' class='update' data-idx='" + actors.length + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");
$(".update").off("click");
$(".update").on("click", selectActor);
};
var deleteActor = function(e) {
$("#deleteActor").on('click', function(event) {
event.preventDefault();
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
});
};
I'm new to jQuery/javascript, and I'm pretty sure its due to the change in DOM, but I just don't know what to change to make it work.
Here is an Example of it in action
Try
var deleteActor = function(e) {
$("#deleteActor").unbind();
$("#deleteActor").on('click', function(event) {
event.preventDefault();
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
});
};
Here is the link for unbind.
http://api.jquery.com/unbind/
The problem is because you're adding another click handler (in jQuery) within the click handler function run from the onclick attribute. You should use one method or the other, not both. To solve the problem in the simplest way, just remove the jQuery code from the deleteActor() function:
var deleteActor = function(e) {
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
};
when you add html dynamically you need to attach the event to the parent static element like so:
$("#actorsTable").on("click","a.update", function() {
$(this).closest("tr").remove();
});

JQuery duplicate events when create element and set events to class

When I add an item using click event and exists another element with the same class the event is duplicated.
$(".add-first").on("click", function() {
var firstContainer='<div class="second-container"><button class="add-second">add second</button></div>';
$(this).closest(".first-container").append(firstContainer);
$(".add-second").on("click", function() {
$(this).closest(".second-container").append("<br>example");
});
});
$(".add-second").on("click", function() {
$(this).closest(".second-container").append("<br>example");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first-container">
<button class="add-first">add first</button>
<div class="second-container"><button class="add-second">add second</button></div>
</div>
Then when I press one click in add first this duplicate event in each button add second, then when I press click on the second button it has some events, the issue is duplicated event.
Try to implement event-delegation instead of binding an event event every time when you are creating a new button,
$(".add-first").on("click", function() {
var firstContainer = '<div class="second-container"><button class="add-second">add second</button></div>';
$(this).closest(".first-container").append(firstContainer);
});
$(".first-container").on("click", ".add-second", function() {
$(this).closest(".second-container").append("<br>example");
});
DEMO

Remove this and only this element jQuery

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

jQuery click event lost after appenTo

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

swapped radio overlaying each other after swapping

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.

Categories

Resources