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;
}
});
Related
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'));
});
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
Can you please tell me how to make this type of list view using jQuery +jQuery UI and jQuery Mobile? I am able to add rows in my list, but I need to add any icon on each row. On Click on each icon it should should this menu option. I am able to make row after click of button. It generate the rows after click of add button. I need to add pop screen on each icon of each row.
http://jsfiddle.net/FZQ8D/24/
function createTestCase(testCaseName,iscreatedFromScript,jsonObject) {
var id;
if (typeof ($("#testCaseContainer li:last").attr('id')) == 'undefined') {
id = "tc_1";
var index = id.indexOf("_");
var count = id.substring(index + 1, id.length);
count = parseInt(count);
var conunter = count;
} else {
id = $("#testCaseContainer li:last").attr('id');
var index = id.indexOf("_");
var count = id.substring(index + 1, id.length);
count = parseInt(count);
var conunter = count;
id = id.substring(0, index) + "_" + parseInt(count + 1);
}
var html = '<div class="testcaselist_row">' + '<ul>' + '<li id="' + id + '" class="clickTestCaseRow">' + id + '</li>' + '</ul>' + '</div>';
$('#testCaseContainer').append(html).enhanceWithin();
}
To get you started, you will need to:
Create a menu handle element that will need to exist inline with your list item.
Create the menu itself. I did this inline but you could have done it somehow else.
Bind an event handler to display or hide the menu onclick. I used a custom data attribute to link the three-dot handle to the appropriate menu div.
I added to your demo to show this basic functionality. It still requires additional work (it still has bugs) but should get you started on extending its functionality to get you to your end goal.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I wrote a code that transform each word in an article to a link, and i wanted to apply onclick() function on the new anchors but the code is not working..
here is the javascript code:
<script>
var tarea = document.getElementById("t");
var div = document.getElementById('res');
var article = tarea.innerHTML;
var i=0;
while(i<500 ){
var ind = article.indexOf(" ");
var curr = article.substring(0,ind);
article = article.substring(article.indexOf(" ")+1);
anch = "<a class='link' id='link' href='#' >" + curr+"</a>";
div.innerHTML = div.innerHTML + " " + anch;
i++;
}
var element = document.getElementById('link');
element.onclick = function () {
alert(element.innerHTML);
};
</script>
This is called event delegation. It can get complicated, but this is the basic concept. You can use anything that can identify the element, but I just used id here since that is the most simple.
var MY_DYNAMIC_EL_ID = 'dynamic';
window.addEventListener('click', function(e) {
var el = e.srcElement || e.target;
if(el.id == MY_DYNAMIC_EL_ID) {
alert('clicked');
}
}
var el = document.createElement('div');
el.id = MY_DYNAMIC_EL_ID;
document.body.appendChild(el);
http://jsfiddle.net/B7Ja9/6/
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
i'm trying to make a script that when i click on a list it add a div inside the tag <li>, this one is ok, but my problem is that when i click in a other <li> i would like remove the div before inserted how can i do that and i would like remove the class .selected as well? Thanks.
$(document).on('click', '#horiz_container img', function() {
var img_selected = $(this);
var value_sport = img_selected.val();
if (!$(this).closest('li').is('.selected')) {
$(this).closest('li').addClass('selected');
$(this).closest('li').prepend('<div class="selected_sport"><img src="' + CI_ROOT +'resources/img/select.png"></div>');
}
});
Try
$(document).on('click', '#horiz_container img', function () {
var img_selected = $(this), $li = img_selected.closest('li');
var value_sport = img_selected.val();
var $selected = $('#horiz_container .selected').removeClass('selected');
$selected.find('.selected_sport').remove();
$li.addClass('selected');
$li.prepend('<div class="selected_sport"><img src="' + CI_ROOT + 'resources/img/select.png"></div>');
});
$(document).on('click', '#horiz_container img', function() {
var img_selected = $(this);
var value_sport = img_selected.val();
if (!$(this).closest('li').is('.selected')) {
$(this).closest('li').addClass('selected');
**$('.selected_sport').remove();**
$(this).closest('li').prepend('<div class="selected_sport"><img src="' + CI_ROOT +'resources/img/select.png"></div>');
}
});