Jquery dynamic element selector - javascript

I know this question has been answered a lot, but when I applied this solution Event binding on dynamically created elements? the selector selects all the elements and retrieved only the first element
$('body').on('click','a.delete',function() {
var id = $('a.delete').attr('id');
var par = $('a.delete').closest('.foo');
console.log(id);
par.hide();
postDelete(id);
});
.foo is a parent element of a.delete
this code hides all elements with class .foo and delete the first element with class a.delete not the clicked one
How can I retrieve the ID of the element I clicked and hide its parent?

You should use this instead of a.delete in click event to get the reference of clicked a.delete like following.
$('body').on('click', 'a.delete', function () {
var id = $(this).attr('id'); //change here
var par = $(this).closest('.foo'); //change here
console.log(id);
par.hide();
postDelete(id);
})

Use this to get the clicked element.
From the docs, In addition to the event object, the event handling function also has access to the DOM element that the handler was bound to via the keyword this
$('body').on('click', 'a.delete', function() {
var id = $(this).attr('id');
var par = $(this).closest('.foo');
console.log(id);
par.hide();
postDelete(id);
});

Related

Which selector will be used when $(this) is called from an event with multiple elements?

I have multiple selectors in a function with onclick event. And I want to update a global variable based on whichever one is clicked.
var sort = '';
$('#firstName, #lastName, #age, #yearLevel, #gender, #event, #year').onclick(function () {
sort = $(this).attr('id');
});
Will the $(this) use the value of the id which was clicked or all of them?
Question 2:
The ids are for <a>, can I use value attribute in <a>, instead of just getting the id name?
Use click instead of onclick.
var sort = '';
$('#firstName, #lastName, #age, #yearLevel, #gender, #event, #year').click(function ()
{
sort = $(this).attr('id');
});
See Plunker: http://plnkr.co/edit/4mEvS5UE7smOpMFw?open=lib%2Fscript.js

JQuery removing <li> using onclick event

I have a ul in which I'll add elements using JQuery, I have this
function addElement(e) {
let text = $('#itemToAdd').val();
let newItem = $('<li>' + text + '</li>');
let removeBtn = $('<button onclick = "removeElement">X</button>');
newItem.append(removeBtn);
$('#shoppingList').append(newItem);
$('#itemToAdd').val('');
e.preventDefault();
}
$(document).ready(function() {
$("#addBtn").on('click', addElement);
});
For removing the elements I have this:
function removeElement() {
$(this).parent().remove();
}
The adding function works awesome, but the removing one doesn't.
If you are using onclick then you have to invoke the function with the reference since this won't refer to clicked element(refers to window object most commonly) and based on that remove that element.
Element creation:
let removeBtn = $('<button onclick = "removeElement(this)">X</button>');
Function :
function removeElement(ele) {
$(ele).parent().remove();
}
Or alternately you can use the existing function but bind event handler using jQuery after element creation.
let removeBtn = $('<button>X</button>');
removeElement.click(removeElement);
An another option would be event delegation which helps to handle events on dynamically created elements.

JQuery - Get the ID attribute of li element

I have a pagination control who's <li> elements are dynamically set and assigned a ID. Using jQuery I am then attempting ti retrieve these set ID's
<div class="col-lg-12 text-center">
<ul class="pagination" id="pagHolder"></ul>
</div>
<script>
$(document).ready(function () {
//*****Logic for setting 'mainArrayHolder'*****
for(var i = 0; t < mainArrayHolder.length; i++)
{
$('#pagHolder').append('<li id="'+i+'">'+ i +'</li>');
}
});
</script>
The Issue I have is I am receiving an 'undefined' error when using the following function:
$(this).click(function(){
var id = $(this).attr("id");
alert(id);
});
I understand this is because 'this' is looking at the whole of the DOM rather than just the <li> elements. How do I set this code so it will get the id attribute of any of the <li> elements a user clicks?
You need to update the selector for your click event.
The following should work:
$('#pagHolder').on('click', 'li', function() {
alert( $(this).attr('id') );
});
Notice that we use the on() function, and delegate the event to any li which exists now (or in the future) as a child node of pagHolder.
Alternatively, you don't need to use jQuery's attr() function inside of the event handler, since this relates to the DOM node itself, you can access its properties directly, for example:
$('#pagHolder').on('click', 'li', function() {
alert( this.id );
});
You are appending li's to #pagHolder list, so you could get ids like this, for example:
$('#pagHolder').on('click', 'li', function() {
var id = this.id;
alert(id);
});

Can't get cloned element to keep originals events

I'm trying to clone an element that is passed into a function and all events associated to it, as there are $('.example').on('click', function(e) ... )} events like this defined in document ready.
So I do following:
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
and I try to clone this element along side its events here (I need to grab parent as .html() returns only inner html, hence element itself) :
function surpriseMe(element) {
var newElement = element.parent().clone(true,true).html();
surprise.insertBefore(element.parent());
if (numElements == 3) {
newMonth = $('<li class="item-dragable-placeholder">'+ newElement +'</li>
}
}
I believe true, true inside .clone() should force parent also grab its children events, but whenever I click on newly placed element, nothing happens
To use event delegation...
Change:
$('.example').on('click', function(e) { ...
To:
$(document).on('click', '.example', function(e) { ...
Note: Instead of using document, find the closest ancestor element (container) that's available on page load and use that.
when you do your insert, instead of inserting the new element, you ask to insert only the html, remove the html part, it will give you the element and its functionalities.
var newElement = element.parent().clone(true,true).html();
See the following (example)[http://jsfiddle.net/dshun/1j9khfnc/4/](please note, since the example code given is not complete. For example, the variable surprise, numElements are not declared. I made some assumptions in my fiddle)
$(document).ready(function(){
var numElements=0;
function surpriseMe(element) {
var newElement = element.parent().clone(true,true);
newElement.insertBefore( ".inner" );
numElements++;
if (numElements == 3) {
newMonth = $('li.item-dragable-placeholder').insert(newElement);
}
}
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
});

Can you target an elements parent element using event.target?

I am trying to change the innerHTML of my page to become the innerHTML of the element I click on, the only problem is that i want it to take the whole element such as:
<section class="homeItem" data-detail="{"ID":"8","Name":"MacBook Air","Description":"2015 MacBook A…"20","Price":"899","Photo":"Images/Products/macbookAir.png"}"></section>
Whereas the code that i have written in javascript:
function selectedProduct(event){
target = event.target;
element = document.getElementById("test");
element.innerHTML = target.innerHTML;
}
will target the specific element that i click on.
What i would like to achieve is when i click on anywhere in the <section> element, that it will take the innerHTML of the whole element rather than the specific one that i have clicked.
I would presume it is something to do with selecting the parent element of the one that is clicked but i am not sure and can't find anything online.
If possible i would like to stay away from JQuery
I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.
Otherwise parentNode might be what you're looking for.
link to currentTarget
link to parentNode
To use the parent of an element use parentElement:
function selectedProduct(event){
var target = event.target;
var parent = target.parentElement;//parent of "target"
}
handleEvent(e) {
const parent = e.currentTarget.parentNode;
}
function getParent(event)
{
return event.target.parentNode;
}
Examples:
1. document.body.addEventListener("click", getParent, false); returns the parent element of the current element that you have clicked.
If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){
var parentElement = getParent(event);
}
var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ; i<_RemoveBtn.length ; i++){
_RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
console.log(event.currentTarget.parentNode);
}
$(document).on("click", function(event){
var a = $(event.target).parents();
var flaghide = true;
a.each(function(index, val){
if(val == $(container)[0]){
flaghide = false;
}
});
if(flaghide == true){
//required code
}
})

Categories

Resources