jQuery `.parent().remove()` is not working - javascript

The solution may be obvious, but when clicking the .remove element, I am trying to remove the entire .tag element that is the parent. Currently, clicking the .remove element has no response.
HTML
'<div class="tag"><input id="' + id + '" type="hidden" name="' + name + '" value="' + value + '" />' + input + '<i class="remove dismiss fa fa-remove"></i></div>'
JS
$('.remove').on('click', '.remove', function() {
$(this).parent().remove();
});

Try this : As you are adding remove link dynamically, you need to register click handler using .on(). But in your case you have error in using .on(). Please use below code.
$(document).on('click', '.remove', function() {
$(this).parent().remove();
});
More Information on jQuery .on()

You can try this:
http://jsfiddle.net/myyzrwwe/
$('.remove').on('click', function() {
$(this).parent().remove();
});

You shouldn't always use delegate the event to the same element that has been delegated. You need to select a static parent. In my example, the document object is the parent of everything.
$('body').on('click', '.remove', function() {
$(this).parent().remove();
});

The problem might be you are binding the event to .remove, if this content is dynamic you might have a problem. Its better, in those cases, to bind to document.
$(document).on()
The callback has the event parameter, use that to remove.
function(e) {
$(e.currentTarget).parent().remove();
}
Check if you undelegate elements.

Related

JQuery on() method not binding events but works in console

I'm writing some TS code to generate a button dinamically, the button appear on page, but all events on it not works.
I already read answers about delegation and I using it, but the problem is not solved.
The most strange thing is that if I call $("#myID").click() or .mouseover() or .mousedown() in console, all events works correctly.
EDIT AND CLOSE:
Sorry for waste of time, I just put to my background the z-index css attribute to -100, and I don't know why, but the button was impossible to be clicked cause, even if it was visible, it was behind the background div.
Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $( "body" ).on( "click", "#commentForm .addNew", addComment ) use $( "#commentForm" ).on( "click", ".addNew", addComment ).
https://api.jquery.com/on/
I suspect your delegation is too complex. Consider the following example.
$(function() {
$("#add").click(function(e) {
var item = $("<div>", {
id: "image-button-1",
class: "button"
}).appendTo("#container");
$("<img>", {
src: "https://i.imgur.com/9yMnjGx.png"
}).appendTo(item);
});
$("#container").on("click", "#image-button-1", function(e) {
console.log("Click");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<div id="container"></div>
Edit: Please don't refer to this, it is incorrect
Can you try this. Enclosing your logic in a function and passing it to jQuery ensures that it is called after the page is loaded completely.
When you are trying to bind event handlers to an element, you have to ensure that the element is actually present in the DOM.
this.htmlElement = "<div id='" + this.ID + "' class='" + this.cssClasses + "'>" + this.buttonImage + "</div>";
$("#" + this.idContainer).append(this.htmlElement);
$(function() {
if (this.enabled) {
$(document).on('mousedown', "#" + this.ID, function (event) {
console.log("down");
});
$(document).on("mouseup", "#" + this.ID, function () {
console.log("up");
});
$(document).on("click", "#" + this.ID, this.action);
}
});

"$(...).find(...)" in onclick-eventhandler

I am using this code for the click handling on a button inside my page:
$(document).on("click", $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection"), function (e) {
addItemToDocumentGrid();
$('#removeDocumentFromSection').disable(true).addClass("disabled");
$('#removeSelection').disable(true).addClass("disabled");
});
But the event fires as soon as I click anywhere in the page. Even if it is not the supposed button which I want to select with $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").
$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection") returns one element which is actually the button which I want to be selected.
Why does it behave like that?
If you want to use event delegation, the second argument should be a selector, not a jQuery object.
$(document).on("click", '#' + GlobalVariables.currentUserType + " .addDocumentToSection", function (e) {
// ---------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
addItemToDocumentGrid();
$('#removeDocumentFromSection').disable(true).addClass("disabled");
$('#removeSelection').disable(true).addClass("disabled");
});
If you don't want to use event delegation, you need to call on on the element you want to hook the event on:
$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").on("click", function (e) {
addItemToDocumentGrid();
$('#removeDocumentFromSection').disable(true).addClass("disabled");
$('#removeSelection').disable(true).addClass("disabled");
});
This is all covered in the on documentation.
You are attaching onClick event to a document element. Try:
var button = $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection");
button.on("click", function() {
addItemToDocumentGrid();
$('#removeDocumentFromSection').disable(true).addClass("disabled");
$('#removeSelection').disable(true).addClass("disabled");
});
$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").on("click", function(e){
});
jQuery can use selectors before the .on("click", this should work for you.

After appending an element the event click is not working on the appended element in jQuery

I am appending item by jQuery. But after appending can't bind the event on the appended item. I am appending as follows:
var item = '<div id="'+newInputId+'" class="col-md-9" style="padding-right: 0px;">';
item += '<input id="txtInScope" type="text" value="'+currentScopeVal+'" class="form-control" readonly="readonly"/>';
item += '</div>';
item += '<div id="inScopeActionDiv'+newInputId+'" class="col-md-3" style="padding-left: 2px;">';
item += '<button type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>';
item += '</div>';
$('#inScopeDiv').append(item);
And after appending this I want to bind a click event on the above remButton class as below:
$("#inScopeDiv").delegate(".remButton", "click", function(){
alert('you clicked me again!');
});
$('#inScopeDiv').on('click', '.remButton', function() {
alert("working");
})
$('.remButton').live('click', function() {
alert('live');
})
But no result. What can I try next?
$('.remButton').live('click', function() {
alert('live');
})
jquery method live is not valid anymore:
"As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()."
Source: jquery live
Little explanation about event attachment:
You must realize that a target what you want to add a event, exists BEFORE to call the add event function(in this case with the method on of jQuery).
on another hand, exists with jquery a manner to make work a event attachment without the existence of the element before:
$('html').on('click', '#inScopeDiv .remButton', function () {
alert('works!');
});
Bind it on a parent that is not dynamic but always in the DOM.
You need to add the listener each time you add an item:
$('#inScopeDiv').append(item)
.off() //unbind old listeners so no duplicate listeners
.on('click', '.remButton', function() {
alert("working");
});
You could store the appended div in a variable using .appendTo and then you could attach the click event directly to the variable. See it working: JSFiddle
$(".appendDiv").click(function () {
var item = "<div>I'm a new div!</div>";
var appended_div = $(item).appendTo(".container");
appended_div.click(function () {
alert("Working!");
});
});

Dont understand why .remove() not working [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
Hi I am learning jQuery and I do not understand why this fucntion does not work. When I click the button it should remove the div but it does not.
The remove function
$(".editButton").click(function () {
$(".editButton").remove();
});
Function that creates the div
var formatPost = function (d) {
var s = '';
s = '<div class="post" data-id="' + d.id + '"><h2 class="postHeading">' + d.title + '</h2>';
s += d.body;
s += '<p> Posted on: ' + d.date + '</p>';
s += '<div class="btn editButton">Edit Post</div>'
s += '</div>'
return s;
};
Currently you are using direct binding, this works when the element exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using .on() delegated-events approach.
i.e.
$(document).on('event','selector',callback_function)
Use,
If you want to remove only button
$(document).on('click', '.editButton', function () {
$(this).remove();
});
If you want to remove complete post, First, You need to execute the action in current element context so use this.
Then use closest() to find post parent and then use .remove()
$(document).on('click', '.editButton', function () {
$(this).closest('.post').remove();
});
Since you are dynamically creating div, use event delegation
$(document).on('click', '.editButton', function () {
$(this).remove();
});
Use Event Delegation.
You added the edit button dynamically. DOM didn't know when was the element is added so we need to traverse from the document or the body or Immediate parent selector to find the element
$(document).on('click', '.editButton', function () {
$(this).remove();
});

Remove buttons added by jQuery

I am adding extra selects and text fields to a form using jQuery. However I want to be able to remove added text fields using the remove button.
Once a field has been added jQuery can not seem to detect it.
jQuery
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'contact-list-div-' + counter).attr("class", 'contact-list-div');
newTextBoxDiv.after().html('<select></select>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >' + '<button type="button" class="removeButton" id="removeButton-' + counter + '">Remove Button</button>');
newTextBoxDiv.appendTo("#contact-list");
counter++;
});
$(".removeButton").click(function() {
alert(this.id); //this never shows, only on the element that was
//added directly added using html, in this case removeButton-1
});
HTML
<div id="contact-list">
<div class="contact-list-div" id="contact-list-div-1">
<select></select>
<input>
<button type='button' class='removeButton' id='removeButton-1'>Remove Button</button>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
$('#contact-list').on('click', '.removeButton', function() {
//Your code
});
You need to use event-delegation:
$(document).on('click', '.removeButton',function() {
$(this).parents('.contact-list-div').remove();
});
You appending content to your DOM after the event-listener for your click on .removeButton is registered. So this element does not exist at the time your binding a click event to it.
Through event-delegation you are able to bind an event-listiner to an existing parent (document in this case, but #contact-list would be working too). And this will listen to all events of its descendants matching the .removeButton - selector.
Demo
This is because you are binding the events to elements that do not yet exist.
Use jQuery delegation to enable handlers on not yet existing elements:
$("body").on("click", ".removeButton", function() {
alert(this.id);
});
You add the click listener only at the first button.
Try using delegate:
$(document).delegate(".removeButton", "click", function() {
alert(this.id);
});
This tells the document that whenever a event click occours on an element with class "removeButton" it should call that callback
(You can see it working here)
Because the element is dynamicly added with jQuery, the normal .click event of jQuery will be not able to detect the new added elements.
Use instead .on. See the example below:
$("body").on("click", ".removeButton", function() {
alert(this.id); //this never shows, only on the element that was
//added directly added using html, in this case removeButton-1
});

Categories