This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I have some javascript which generates some html elements, like below:
for (var i = 0; i < suggestions.length; i++) {
var suggestion = suggestions[i];
var $li = $('<li data-profile-id="'+ suggestion.id + '" data-profile-name="'+suggestion.first_name + ' ' + suggestion.last_name + ' " class="search-name-result" ></li>');
$suggestionsUl.append($li);
var $img = $('<img src="/img/profile/' + suggestion.picture_url + '" class="search-suggest-img pull-left" />');
$li.append($img);
var $link = $('' + suggestion.first_name + ' ' + suggestion.last_name + '');
$li.append($link);
}
What I need to be able to do is also assign a function to each dynamically created li element, something like the below code:
$('.search-name-result').on('click', function(e){
$input.val($('.search-name-result').data('profile-name'));
});
But im not sure how to assign this to each li when they are created.
Thanks
Almost there, but actually delegate it using a parent container like document
$(document).on('click','.search-name-result', function(e){
$input.val($(this).data('profile-name'));
});
Also, you can change
$('.search-name-result').data('profile-name'))
to use $(this) like
$(this).data('profile-name'))
since it will be the clicked .search-name-result
You should use event delegation for dynamically added elements.
$(document).on('click','.search-name-result', function(e){
$input.val($('.search-name-result').data('profile-name'));
});
Related
This question already has answers here:
Click event doesn't work on dynamically generated elements [duplicate]
(20 answers)
Closed 4 years ago.
I'm getting an error when setting on click to the dynamically added html elements in jquery.
First of all i should say that i searched alot in this community but i get more confused .
here is my code :
var data = ['element1','element2','element3'] ;
var html = '' ;
for(let i = 0;i<data.length ; i++){
const element = data[i];
html += '<li id="'+element+'">'+element+'</li>' ;
}
I Want to add different click functions to every list item in this code using ids .
any suggestions will be helpfull , thanks to this great community .
Here is an example using plain JavaScript showing how you can attach such click handlers to your dynamically created elements.
First you need to create the li's using document.createElement, then you set the text content and id of your li's.
The click handler can be added by setting the onclick property or using the addEventListener method.
Once your li is set, you just have to append it to a container, here a list <ul>.
const elements = ['element1','element2','element3'];
const handlers = [
() => console.log('hello 1'),
() => console.log('hello 2'),
() => console.log('hello 3')
];
const content = document.getElementById('content');
elements.forEach((id, i) => {
const li = document.createElement('li');
li.id = id;
li.textContent = `Hello ${i}`;
li.addEventListener('click', handlers[i]);;
content.appendChild(li);
});
<ul id="content"></ul>
You can use document selector for dynamically created DOM elements.
eg: for element1
$(document).on("click","#element1",function(){
//your code snippet
});
You can attach the click event on the parent element, in this case, the <ul> element. In jQuery, the .on() function has a second selector parameter which can be the li in this case.
Within the callback function, you can use $(e.target).attr('id') to find the id of the current element being clicked. This can be used to take appropriate action based on its value.
See the code below.
var data = ['element1', 'element2', 'element3'];
var html = '';
html += '<ul id="ulElement">';
for (let i = 0; i < data.length; i++) {
const element = data[i];
html += '<li id="' + element + '">' + element + '</li>';
}
html += '</ul>';
$('#content').html(html);
$('#ulElement').on('click', 'li', function(e) {
var clickId = $(e.target).attr('id');
console.log(clickId)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content"></div>
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
SOLVED: Not enough coffee - the event listener was being added before the buttons were created.
Im creating a table from HTML LocalStorage like so:
for (i = 1; i <= localStorage['count']; i++) {
tableHtml = tableHtml + "<tr><td><button class='delete' id=" + i + ">Delete</button></td><td>" + localStorage['fullName' + i] + "</td><td>" + localStorage['email' + i] + "</td><td>" + localStorage['phoneNum' + i] + "</td></tr>";
}
This works great, however the delete button is proving troublesome.
I saw this:
jQuery find ID of clicked button by class
So I assumed i could do this:
$(".delete").click(function () {
alert('delete clicked for id: ' + $(this).id);
});
However, it doesn't work. Suggestions?
you can get the id of element by using javascript without using jquery wrapper like this:
$(".delete").click(function () {
alert('delete clicked for id: ' + this.id); // get id via javascript
});
or:
$(".delete").click(function () {
alert('delete clicked for id: ' + $(this)[0].id); // via javascript object
});
If you see the link reffered in question it is also getting id using javascript (this.id)
if you want to get via jquery then:
$(".delete").click(function () {
alert('delete clicked for id: ' + $(this).attr("id")); // via jquery object
});
When are you binding the click event? If it's before the element exists, you'll want to use .on.
$('body').on('click','.delete', function(){
alert('delete clicked for id: ' + $(this).attr('id'));
});
Check out a working jsFiddle.
use pure javascript:
this.id
or jquery
$(this).attr('id');
as $(this) is jquery object. and you are trying to get javascript property id. You need to first convert the object to javascript.
$(this)[0].id;
DOM elements shouldn't have numbers as the first character of id.
Change your code to something like this:
for (i = 1; i <= localStorage['count']; i++) {
tableHtml = tableHtml + "<tr><td><button class='delete' id=del-id" + i + ">Delete</button> </td><td>" + localStorage['fullName' + i] + "</td><td>" + localStorage['email' + i] + "</td><td>" + localStorage['phoneNum' + i] + "</td></tr>";
}
And
$(".delete").click(function () {
alert('delete clicked for id: ' + $(this).prop('id');
});
This should take you on the right track.
REMEMBER that .prop() function is jQuery 1.10+ specific.
If you are using an older version use .attr()
As some people here mentioned - id's can be numeric as of HTML5
still using them in a numeric form might generate rather unpleasant problems.
Link in the comments below from one of the users.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I would like to know, how to create selector, that links to dynamically created element, without using event on the dynamically created element?
NOTE: dynamically created element I mean element, that is not in HTML at the beginning
I know that I can use $(this), when I have event (for example .click) on the element, but when I don't have event and I need selector on the dynamically created element?
Thanks to all.
update: Here is my situation:
$(".product div a").click(function() {
var nameOfProduct = $(this).parent().find("h3").text();
var dataPrice = parseInt($(this).parent().find("div b").text());
var isProductIn = false;
var itemsInDay = $(/*HERE I NEED THE SELECTOR*/).find("div.item").nextUntil("div.center");
itemsInDay.each(function () {
if (nameOfProduct == ($(this).find("span ins span").text())) {isProductIn = true;};
});
if (isProductIn) {
//add only +1, not new product again;
} else {
var imgOfProduct = $(this).parent().parent().find("img").attr('src').replace('med', 'min');
var product = ('<div class="item" data-price="' + dataPrice + '"><img src="' + imgOfProduct + '"><span><ins><b>1x</b> ' + nameOfProduct + '</ins><img src="images/delete.png"></span></div>');
$(product).appendTo(".dayOrder:last").delay(800).hide().slideDown();
}
return false;
});
Try something lihe this http://jsfiddle.net/pEb7D/5/
HTML:
<div class="test"></div>
Javascript:
dynamicSelector = $('.test').append('<div class="newElement">Hello!</div>');
setTimeout(function () {
dynamicSelector.text('Goodbye!');
}, 3000);
UPDATE:
OK, so you're putting the items into the .orderDay:last element. There you could loop through it's contents and see if you already have an existing element of one or other type.
However I would recommend making an array according to the product ID and then reacting to that.
For example http://jsfiddle.net/8byQp/
Javascript:
daysOrderArray = [];
$(".product div a").click(function() {
var nameOfProduct = $(this).parent().find("h3").text();
var imgOfProduct = $(this).parent().parent().find("img").attr('src').replace('med', 'min');
var dataId = $(this).parent().parent().data("id");
var dataPrice = parseInt($(this).parent().find("div b").text());
priceSum += dataPrice;
updatePrice(priceSum);
if(dataId in daysOrderArray){
// Now add number rather than new product.
daysOrderArray[dataId]++;
$('.item[data-id="' + dataId + '"] .quantity').text(daysOrderArray[dataId]);
} else {
daysOrderArray[dataId] = 1;
var product = ('<div class="item" data-id="' + dataId + '" data-price="' + dataPrice + '"><img src="' + imgOfProduct + '"><span><ins><b><span class="quantity">1</span>x</b> ' + nameOfProduct + '</ins><img src="images/delete.png"></span></div>');
$(product).appendTo(".dayOrder:last").delay(800).hide().slideDown();
return false;
}
});
This question already has answers here:
How to increment div id value?
(3 answers)
Closed 9 years ago.
I have a horizontal menu. I want to create an id for each using jQuery. My code is:
<div class="menuBar">
<div class="menuHeader ui-corner-top">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top">
<span>New Transaction</span>
</div>
</div>
Here menu has no id. I want to create id dynamically using jQuery. How can I do this? I did an example like this, but it is not working:
var i = 0;
$('.menuHeader').each(function () {
i++;
newID = menu + i;
$(this).attr('id', newID);
$(this).val(i);
});
The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.
You have also omitted the quotes when you concatenated menu string with i variable.
$('.menuHeader').each(function (i) {
$(this).find('a').attr('id', 'menu' + (i + 1));
$(this).html((i + 1) + '. ' + $(this).html());
});
jsFiddle Demo
Try this, no need of extra variable i:
$('.menuHeader').each(function () {
$(this).attr('id', 'menu' + ($(this).index() + 1));
$(this).val($(this).index() + 1);
});
Try this
$('.menuHeader').each(function (i) {
newID = "menu_" + i;
$(this).attr('id', newID);
$(this).val(i);
});
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I add a DOM element with jQuery?
var re = new RegExp("\\b(" + l + ")\\b")
var sOpen = "<span class='highlight'>";
var sClose = "</span>";
var newhtml = sp.replace(re, sOpen + l + sClose, "gi");
alert(newhtml);
$('.highlight').css('color', 'yellow');
I am getting newHtml value as
I love to work with <span class='highlight'>jquery</span>
I am highlight the highlight class item. jquery but its not hightlighting the text. please can any body tell me is that something I am doing wrong here?
how to create a newhtml as DOm element?
thanks
Even better would be to wrap it with the built-in logic:
$('myelement').wrap('<span/>').parent().addClass('highlight');
You can create an object of it and add it to the DOM:
var newhtml = $(sp.replace(re, sOpen + l + sClose, "gi"));
$(body).append(newhtml);