How can I manipulate dynamically created elements wth jquery? - javascript

I am a jquery newbie and i am creating boxes with jquery and then "deleting" them. But I want to use the same code to delete the box in the scope of the created element and the scope of a already created element.
Html:
<button id="create">Cria</button>
<div id="main">
<div class="box">
<a class="del-btn" href="#">Delete</a>
</div>
</div>
JS:
var box = {
create: function() {
var box = $('<div class="box">');
var delBtn = $('<a class="del-btn" href="#">Delete</a>');
box.appendTo('#main');
delBtn.appendTo(box);
},
destroy: function(elem) {
elem.fadeOut();
}
}
function deleteBox () {
}
$(function() {
$('#create').click(function() {
box.create();
});
$('.del-btn').click(function() {
var elem = $(this).parent();
box.destroy(elem);
return false;
});
});
If I put the delete event inside the create click event, I just can delete the dynamically created element. If I put it outside, then I can just delete the element in the HTML. I know this is a simple question, but I can't figure out how to solve it. Thanks

You can use delegated-events approach:
$("#main").on("click", ".del-btn", function() {
var elem = $(this).parent();
box.destroy(elem);
return false;
});

Related

Add click event on a dynamically created element in Javascript

I am trying to add a click event on an element which i create dynamically in Vanilla JS. With jquery its super simple all i would do is
$(document).on('click','.el', function() {
//somecode
})
However with Vanilla JS (because i'm using react) i can't do the same thing.
I've tried adding the dynamic element as an argument just like i would in jquery but no money.
I'm sure it can be done just not the way i'm thinking. Any ideas?
I tried
let div = document.createElement('DIV')
div.classList.add('el')
document.addEventListener('click','.el', function() {
//some code
})
I also tried
document.addEventListener('click',div, function() {
//some code
})
None of these methods worked
let div = document.createElement('DIV');
div.classList.add(".whatever");
div.addEventListener('click', function() {
console.log('dynamic elements')
});
document.body.appendChild(div);
https://jsfiddle.net/yu1kchLf/
You could simply use and onclick function and just call it as variable from your dynamically added elements.
Live Demo
//Create function
let button = document.createElement('button');
button.classList.add("myBtn");
button.innerText = 'Click Me';
button.onclick = myFunction //assign a function as onclick attr
document.body.appendChild(button);
//Call function
function myFunction() {
console.log('I am being called from dynamically created button')
}
i think what you are missing is appending the element you created to your DOM.
have a look at this:
var createDiv = function() {
let div = document.createElement('DIV');
div.id = 'el';
div.innerHTML = '<b>hey</b>';
div.classList.add('styles');
document.body.appendChild(div);
div.addEventListener('click', function() {
alert('Look here');
})
};
here's a fiddle so you can playaround: https://jsfiddle.net/khushboo097/e6wrLnj9/32/
You can do something like the following:
const d=document.getElementById("container");
document.addEventListener('click', function(ev) {
if (ev.target?.classList.contains('el')) {
console.log("My .el element was clicked!");
ev.target.classList.contains("segundo") &&
(d.innerHTML+='<p class="el">another clickable paragraph</>');
}
})
<div id="container"><h2>Something unclickable</h2>
<p class="el primero">A clickable paragraph!</p>
<p class="otro primero">something unclickable again ...</p>
<button class="el segundo">add clickable element</button>
</div>
The event handler is attached to the document itself but will only fire the console.log() if the ev.target, i. e. the clicked element, is of class "el".

Is it allowed to use jQuery $(this) selector twice in a function and in an included each loop?

I have a list, which contents x columns of data. When clicking an edit button in a row, I want to set the html content of each column of this row, which has a name attribute into an array, which key is named by the columns name attributes value.
data['id'] = '123';
data['name'] = 'John Doe';
data['city'] = 'Arlington';
For that I'm starting a click event on the edit div. Inside this function I'm working with $(this) selector for setting up an each() loop over all elements having a name attribute.
Inside this loop I'm catching the names and values of each matched element with $(this) selector again.
So, my question: although it works - is it allowed to do it this way? Using $(this) for two different things inside the same function?
Is there a different way?
Here is my working example code
$( document ).ready(function() {
$(document).on( "click", ".edit", function() {
var data = {};
$(this).closest('.row').children('div[name]').each(function() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(this).html();
});
$('#result').html(JSON.stringify(data, null, 4));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div name="id">123</div>
<div name="name">John Doe</div>
<div name="city">Berlin</div>
<div class="edit">> edit <</div>
</div>
<br clear="all">
<div id="result"></div>
Is it allowed?
It works, so of course.
Depends on what you mean by "allowed".
Is it confusing - perhaps.
Can it cause problems - definitely.
(There are plenty of questions on SO with this or problems caused by this that confirm it causes problems).
Reusing variable names ('this' in this case) is common and is based on scope.
It's hard to tell if you have a bug because you actually wanted the ".edit" html or the ".edit" attr rather than the div, so you can remove that confusion by copying this to a variable:
$(document).on( "click", ".edit", function() {
var data = {};
var btn = $(this); // the button that was clicked
btn.closest('.row').children('div[name]').each(function() {
// Do you mean the div or did you really mean the clicked button?
data[$(this).attr('name')] = $(this).html();
var div = $(this); // the child div
// clearly not what is desired
// `btn` variable referring to the outer `this`
data[div.attr('name')] = btn.html();
// intention clear
data[div.attr('name')] = div.html();
});
$('#result').html(JSON.stringify(data, null, 4));
});
In this case, it's "clear" as you wouldn't use the btn html on all the data entries (or would you? I don't know your requirements...). So "unlikely".
But it's easy to see how, in another scenario, you would want to refer to what was clicked btn==this inside the nested .each.
Try this trick:
$( document ).ready(function() {
$(document).on( "click", ".edit", function() {
var data = {};
var that = this; // trick here
$(this).closest('.row').children('div[name]').each(function() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(that).html();// replace this = that if you want to get parent element
});
$('#result').html(JSON.stringify(data, null, 4));
});
});
there is nothing wrong, what you do is simply this
function setDivs() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(this).html();
}
function docClick(){
var data = {};
$(this).closest('.row').children('div[name]').each(setDivs);
$('#result').html(JSON.stringify(data, null, 4));
}
function docReady(){
$(document).on( "click", ".edit", docClick)
}
$( document ).ready(docReady);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div name="id">123</div>
<div name="name">John Doe</div>
<div name="city">Berlin</div>
<div class="edit">> edit <</div>
</div>
<br clear="all">
<div id="result"></div>

Appending an element to a cloned element

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

The show/hide function is not working with the clone function

I have a problem triggering the show() and hide () function in jQuery when I use it together with the .clone() function.
There isn't any problem showing or hiding the first id but when it comes to a cloned id, showing or hiding doesn't work on it.
Here's a sample js of it:
var $country = $('#country')
$('#add-countries').on('click', function () {
$(this).before($country.clone());
});
$('#morelocal').on('click', function () {
$('#showzipcode').toggle();
$('#morelocal').hide();
});
$('#hidezipcode').on('click', function () {
$('#morelocal').show();
$('#showzipcode').hide();
});
Full jsfiddle here: http://jsfiddle.net/stan255/Wh274/7/
Since you are cloning the elements
It is better to use classes instead of ids because id of an element must be unique
And need to use event delegation to support dynamically added elements
so
<div>
<!-- use class instead of id -->
<a href="#" class='morelocal'>
Track ZIP/Postal code
</a>
<!-- use class instead of id -->
<span class='showzipcode'>
<input type="text" placeholder="e.g: 30196"/>
<a href="#" class='hidezipcode'>cancel</a>
</span>
</div>
then
var $country = $('#country')
$('#add-countries').on('click', function () {
var $clone = $country.clone().removeAttr('id');
$(this).before($clone);
$clone.find('.morelocal').show();
$clone.find('.showzipcode').hide();
});
//use event delegation
$(document).on('click', '.morelocal', function () {
var $div = $(this).closest('div');
$div.find('.showzipcode').show();
$div.find('.morelocal').hide();
});
$(document).on('click', '.hidezipcode', function () {
var $div = $(this).closest('div');
$div.find('.morelocal').show();
$div.find('.showzipcode').hide();
});
Demo: Fiddle, Fiddle2

Remove internal selected div created dynamically

I've been looking around but i couldn't find a solution yet.
My code is something like this:
$('#addDiv').click( function() {
var divNum = divNum + 1;
var newdiv = document.createElement('div');
var divIdName = 'mydiv';
newdiv.setAttribute('id',divIdName+divNum);
newdiv.className = 'imgDiv';
});
$('#cont-div').on('click', function(e) {
//REMOVE clicked div
});
I have a div named "cont-div" which contains the dynamically created divs.
Probably the solution is very simple, but I can't find a way to identify the clicked div inside 'cont-div' so I can remove it.
You can use event delegation since the divs are created dynamically:
$('#cont-div').on('click', 'div', function(e) {
//REMOVE clicked div
$(this).remove();
});
$('#cont-div div').on('click', function(e) {
var clickedDiv = e.target;
if(clickedDiv != e.currentTarget)
{
//Remove the clicked div if it is not the parent.
$(this).remove();
}
});
Hmmm, your code implies you may have multiple elements with the same ID. Don't do that, that'll make things harder. Just use the class you have set:
$('.imgDiv').on('click', function() {
$(this).remove();
});
You can use jquery remove() to remove the element. Also you will need a delegate for simply handling events on dynamicly inserted elements.
Working Demo
Html:
<input id="addDiv" type="button" value="click!" />
Javascript:
$(function(){
$('body').on('click','.imgDiv',function(){
$(this).remove();
});
});
EDIT: Shortened down code snippet, now only showing relevant parts.

Categories

Resources