This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I want to remove the parent p tag when the cross button is clicked.
My HTML structure is like this :
jQuery('.delete').click(function() {
jQuery(this).closest('.question-list').remove()
});
jQuery('.add-question-btn').click(function() {
jQuery("#add-question-div-parent").append("<p class='add-question-div' style='position: relative'><input type='text' class='add-ques-text' placeholder='Add Question'><span><i class='fa fa-times cls' aria-hidden='true'></i></span></p>");
});
jQuery('.cls').click(function() {
jQuery('.add-question-div').remove()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<p class="question-list">Here is my question.Here is my question.Here is my question.
<span><i class="fa fa-times delete" aria-hidden="true"></i></span>
</p>
<div id="add-question-div-parent" class="full-width"></div>
<button class="add-question-btn">+</button>
.add-question-div this has been added successfully after '.add-question-btn' button has clicked, but unfortunately i'm not able to remove .add-question-div when i click on .cls.
Any kind of help would be highly appreciated. Thanks.
The .cls element is added dynamically so the click event is not associated at the time of page load so use $(document).on('click','.cls', function(){...});. You also need to delete the particular add-question-div when the icon is clicked so use $(this).closest('.add-question-div').remove();
$('.delete').click(function() {
$(this).closest('.question-list').remove()
});
$('.add-question-btn').click(function() {
$("#add-question-div-parent").append("<p class='add-question-div' style='position: relative'><input type='text' class='add-ques-text' placeholder='Add Question'><span><i class='fa fa-times cls' aria-hidden='true'>X</i></span></p>");
});
$(document).on('click','.cls', function() {
$(this).closest('.add-question-div').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="question-list">Here is my question.Here is my question.Here is my question.
<span><i class="fa fa-times delete" aria-hidden="true"></i></span>
</p>
<div id="add-question-div-parent" class="full-width"></div>
<button class="add-question-btn">+</button>
Related
I have the following code which adds divs within a container (#subtask_container) via clicking a link (similar to Google Tasks):
HTML:
<p class="text-muted">
<i class="fas fa-tasks mr-2"></i>
Add subtasks
</p>
<div id="subtask_container"></div>
JS (this successfully adds unique inputs within the subtask container div along with a clickable x after each input)
var i = 1
$("#add_subtask").click(function () {
$("#subtask_container").append('<input name="subtask'+i+'" class="mt-1" id="subtask'+i+'" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted"></i><br>');
i++;
});
What logic do I need to add to the x class to remove it's associated input?
I've tried
$('.fa-times').click(function(){
$(this).prev('input').remove();
});
but it doesn't seem to work...
Thanks!
You can simply wrap your subtask append in a div and simply use .parent() and .remove() function on that. No need to use <br>
Also, do not use .fa-times as primary click event handler as you might have other fa-times on the same page as well Which might cause issues later on. Add a custom class to your fa item (.subtask_remove_icon)
Live Demo:
var i = 1
$("#add_subtask").click(function() {
$("#subtask_container").append('<div><input name="subtask' + i + '" class="mt-1" id="subtask' + i + '" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted subtask_remove_icon"></i></div>');
i++;
});
$(document).on('click', '.subtask_remove_icon', function() {
$(this).parent().remove(); //remove the input when X clicked
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<p class="text-muted">
<i class="fas fa-tasks mr-2"></i>
Add subtasks
</p>
<div id="subtask_container"></div>
The event handler gets attached to all elements that are on the page load. Since the icons are appended, the right way to do this would be the following:
var i = 1
$("#add_subtask").click(function () {
$("#subtask_container").append('<div><input name="subtask'+i+'" class="mt-1" id="subtask'+i+'" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted removeIcon"></i><br></div>');
i++;
});
$(document).on('click', '.removeIcon', function(){
$(this).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<p class="text-muted">
<i class="fas fa-tasks mr-2"></i>
Add subtasks
</p>
<div id="subtask_container"></div>
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
The user can delete new field input rows by by clicking on the ‘-‘ button for that particular row. The user also has the ability to add new field input rows. The JS code that I've written works for the existing rows, but it doesn't work for any of the new dynamically created lines that are added by clicking the '+' button.
I've tried changing
$(".remove-current-ing").click(function() {...}
to
$(".remove-current-ing").on('click', function() {...}
HTML code:
<div class="row card z-depth-1">
<h3><i class="fas fa-pizza-slice"></i> Ingredients</h3>
{% for ing in recipe.ingredients %}
<div class="input-field ingredients col s12">
<input id="ingredients" name="ingredients" type="text" placeholder="Ingredient (one per line)" class="form-control validate" value="{{ ing|capitalize }}" required>
<label for="ingredients"></label>
<!--BUTTON THAT ISN'T WORKING ON DYNAMICALLY CREATED ROWS-->
<a class="waves-effect waves-light btn remove-current-ing">
<i class="fas fa-minus material-icons" aria-hidden="true"></i>
</a>
</div>
{% endfor %}
<!--Add Ingredient Row Btn-->
<button type="button" class="waves-effect waves-light btn add-ing">
<i class="fas fa-plus material-icons" aria-hidden="true"></i>
</button>
<!--Remove Ingredient Row Btn-->
<button type="button" class="waves-effect waves-light btn remove-ing">
<i class="fas fa-minus material-icons" aria-hidden="true"></i>
</button>
</div>
JS code:
let ingCount = $(".ingredients").length;
// Add new line
$(".add-ing").click(function() {
// Clone line, insert before add/remove btns and clear existing values
$(".ingredients:first").clone().insertBefore(".add-ing").find("input[type='text']").val("");
// Ensures original line is never removed
ingCount += 1;
});
// Remove last line
$(".remove-ing").click(function() {
// Ensure that the first line can't be removed
if (ingCount > 1) {
$(".ingredients:last").remove();
ingCount -= 1;
}
});
/* Remove the current ingredient (edit_recipe.html) */
/* CODE THAT ISN'T WORKING ON DYNAMICALLY CREATED ROW */
$(".remove-current-ing").on('click', function() {
// Ensure that the first line can't be removed
if (ingCount > 1) {
$(this).parent().remove();
ingCount -= 1;
}
});```
The .remove-current-ing button works on pre-exisiting rows and removes them, but it doesn't work on new dynamically created rows (nothing happens when pressed).
Replace
$(".remove-current-ing").on('click', function() {
with
$(document).on('click', ".remove-current-ing", function() {
This is called delegate listener - the concept is that any click event bubbles up the DOM until it reaches document where your listener is attached. The addition of the selector string as a second parameter to $.on() makes jQuery only execute the handler function if the clicked element matches the selector.
You have to use late binding. It allows you to bind the event on the element which is currently doesn't exist through appropriate attribute
$(document).on('click', ".remove-current-ing", function() {
// Ensure that the first line can't be removed
if (ingCount > 1) {
$(this).parent().remove();
ingCount -= 1;
}
});```
I'm having trouble figuring out why my click event is not firing. I am trying to click on the trash can icon and have a function run that deletes the list element. After the click event, it fails to execute anything else in the script. It doesn't even console.log anything directly below. Below is the markup and my script.
HTML CODE
<div class="col-6">
<div class="js-list-item">
<h3 class="js-list-title"></h3>
<i class="fa fa-pencil" aria-hidden="true"></i>
<i class="fa fa-trash-o" aria-hidden="true"></i>
<p>Date: <span class="js-date"></span></p>
<p>Schedule: <span class="js-schedule"></span> at <span class="js-schedule-time">
</span></p>
</div>
</div>
javascript code
function handleDelete() {
$('.js-list-item').on('click', 'fa-trash-o', function(e) {
console.log('test');
e.preventDefault();
deleteShow(
$(e.currentTarget).closest('.js-list-item').attr('id')
);
});
}
The second parameter of the .on() function is a selector.
http://api.jquery.com/on/
Change:
$('.js-list-item').on('click', 'fa-trash-o', function(e) {
to:
$('.js-list-item').on('click', '.fa-trash-o', function(e) {
('click', 'fa-trash-o', function(e)
fa-trash-o is not a proper selector, use class or id
I'm wanting to use toolbar.js from http://paulkinzett.github.io/toolbar but even though I have the tool bar working the the handling of the events as documented I don't seem to be able to get identify which toolbar button/icon I clicked.
Below is the code snippit, which it pretty much lifted from the example site.
I'm no expert in JS, so if someone could enlighten me as to how to handle the toolbarItemClick event so that I can preform the correct action, that would be awesome.
Thanks
Lionel
<div id="user-options" class="toolbar-icons" style="display: none;">
<i class="icon-edit"></i>
<i class="icon-trash"></i>
</div>
<div class="tooltip-container normal">';
<section class="left">';
<div id="normal-button" class="settings-button"><img src="/3rdparty/paulkinzett-toolbar/documentation/img/icon-cog-small.png" /></div>';
</section>';
</div>
$('#normal-button').toolbar({content: '#user-options', position: 'top'});
$('#normal-button').on('toolbarItemClick',
function(event) {
console.log(event);
}
);
I was trying to figure out the same thing, eventually i deciphered the mechanism. A bit late to help you but maybe it will save someone else some time.
Firstly, I gave the button anchor tags IDs, though one could use data- attributes etc (note i am using img tags instead of the default glyph support)
<div id="user-toolbar-options">
<a id="menu-insert" href="#"><img src="add.png" width="18px" height="18px" /></a>
<a id="menu-remove" href="#"><img src="remove.png" width="18px" height="18px" /></a>
</div>
The key is to use a different function signature which isn't publicized in the documentation (function (event, buttonClicked){}, the 2nd parameter (buttonClicked) is the a element that was clicked on.
in the code below i also set targetBlock to the div that the button was in (as i have potentially dozens of articles and the button thats hows the toolbar appears on each) so i need to get the article in question to act on it.
$('#normal-button').on('toolbarItemClick',
function (event, buttonClicked) {
var targetBlock = $(event.target).parents('.article') // get article
var buttonClickedID = buttonClicked.id // get the id of the button click
switch (buttonClickedID) {
case 'menu-insert':
insertNewArticleBelow(targetBlock)
break;
case 'menu-remove':
removeArticle(targetBlock)
break;
}
}
$('#button').toolbar({
content: '#toolbar-options',
position: 'top',
style: 'primary',
event: 'click',
hideOnClick: true
});
$('#button').on('toolbarItemClick',
function( event,buttonClicked ) {
alert(buttonClicked.id);
}
);
<link href="https://paulkinzett.github.io/toolbar/css/documentation.css" rel="stylesheet"/>
<link href="https://paulkinzett.github.io/toolbar/css/jquery.toolbar.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://paulkinzett.github.io/toolbar/js/jquery.toolbar.min.js"></script>
<div id="toolbar-options" class="hidden">
<i class="fa fa-plane"></i>
<i class="fa fa-car"></i>
<i class="fa fa-bicycle"></i>
</div>
<div data-toolbar="toolbar-options" data-toolbar-animation="flip" class="btn-toolbar feature-toolbar btn-toolbar-primary text-center" data-toolbar-style="primary" id="button"><i class="fa fa-cog" style="position: relative"></i></div>
When I click on the new button with jQuery it adds the div, but it only adds one. When I check from DevTools it constantly creates the same place. But I want it to add another one after that. Can you help me?
HTML code
<div class="text-left" style="margin-bottom: 15px;">
<button type="button" class="add-extra-email-button btn btn-success" disabled><i class="fas fa-plus"></i></button>
</div>
<div class="clone"></div>
Here are the sample js codes
$('.add-extra-email-button').click(function() {
var element = $('.clone');
element.html(
'<div class="clone_edilen_email">' +
'<li>' +
'<a href="javascript:;"> Test' +
'<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' +
'</a>' +
'</li>' +
'</div>'
);
$('.clone_edilen_email').addClass('single-email remove-email');
$('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
$('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
$(document).on('click', '.remove-field-email', function(e) {
$(this).parent('.btn-delete-branch-email').parent('.remove-email').remove();
e.preventDefault();
});
If I understand correctly, you want to add the <div class="clone_edilen_email"> again and again, as soon somebody clicks on the .add-extra-email-button button.
In general, calling element.html('<some_wild_html></some_wild_html>') will always override the full inner content of element with <some_wild_html></some_wild_html>. Also, if the element already contains some other sub-elements, they will got lost. In your given code example, I assume, your intention was to extend the element's html and not replace it.
Here is my suggestion:
$('.add-extra-email-button').click(function() {
var newDiv = $('<div class="clone_edilen_mail"></div>');
newDiv.html('<li><a href="javascript:;"> Test<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i></li>');
$('.clone').append(newDiv); // This is the important clue here!
// afterwards you may insert your residual class stuff
// $('.clone_edilen_email').addClass('single-email remove-email'); <- I would suggest you add these classes already at the begining, where I set the variable "newDiv"
// ...
// $('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
// $('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
// .. your other code may follow here ...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clone">I am a clone-div!</div>
<button class="add-extra-email-button">Click Me!</button>
Hope that this might help you!
Try This Method, Append Duplicate Elements and Contents Using jQuery .clone() Method
<!doctype html>
<html>
<head>
<title>jQuery Clone() – Add Elements and its Contents</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<style>
div {
margin:3px;
padding:3px;
border:solid 1px #999;
width:300px;
}
</style>
</head>
<body>
<p>Click the button to clone (make a duplicate) of the DIV element!</p>
<div id="Container">Hello, how was your day!</div>
<p><input type="button" id="Button1" value="Clone it" /></p>
</body>
<script>
$(document).ready(function () {
$('#Button1').on('click', function () {
$('#Container')
.clone()
.appendTo("body");
});
});
</script>
</html>
In your first click function you replace all the content of your div clone so even if you click again you are going to have only one. He is just replacing the old one.
I didn't get what you are trying to do with the second click function.