Jquery appendTo Duplicating content multiple times - javascript

Every time I use JQuery's AppendTo(), it duplicates the items that I want appended. And every time I load in the page with AJAX (which includes the script) it duplicates it even more times! It only works normal for the first time after the entire page is reloaded.
$("<tr><td><input name='quantity[]'/></td><td><input type='text' name='ItemDescription[]'/></td><td><span class='remove'>X</span></td></tr>")
.appendTo('.tbody');
Please note that I've also tried append(),
and
$('.tbody').html($('.tbody').html() + 'string');
and the same issue persists.

From your description it looks like you are running the script which is registering the event handler multiple times. The best solution is not to do that, ie try to run the script only once.
If you are doing to handle dynamic elements look at event delegation.
If that is not possible, another solution is to remove any handler before adding a new handler so that any given time there will be only one handler. Also you can use event namespace to make sure that you won't remove some other handlers
$('some-selector').off('click.duplicate').on('click.duplicate', function(){})

Try to have a copy initially before doing the appending process,
var copy = $('.tbody').html(); //This should be done initially before making any calls
$('.tbody').html(copy + 'string');
So that you wont append your elements repeatedly.

When you use append(), it will be appended to the existing body (btw I dont know why you append a row to a body. This should be appended to a table). So if you call append() the second time, you will have two rows. Thats exactly what append() does. If you want to redesign the table after each load you have to clear all existing rows with
$('.tbody').html("");
But better use a table in the body and append the row to the table and clear the table.

Related

jquery button click not working , using django templates for rendering

I have multiple buttons on the same page with same id so basically
rendering in a for loop with same id . I set a click event handler in
jquery but it fires for only the first button.
Can you suggest?
You can see the error in console, which probably would be because of same ID for all the buttons. One solution would be to append the index to the button id string so that each button will have unique id(btn1, btn2 etc), or use the class instead of id.
Duplicating ids are causing your HTML to be invalid. Javascript (and jQuery) assumes that there is a single id, therefore:
$("#yourid")
will not search for the id further.
You can sidetrack the issue via
$("[id=yourid]")
which will find all the elements, but that's not advisable, because then your HTML is still invalid. A better approach would be to change your id into a class and use that as a selector afterwards.
EDIT
In jQuery you can create a click event like this:
$("[id=saveFavorite]").click(function() {/*...*/})
But even though this will work, I recommend refactoring your code, changing the HTML you have by replacing every id="saveFavorite" to class="saveFavorite" and do it like this:
$(".saveFavorite").click(function() {/*...*/})

Datatable dynamically created table not sortable

I have few DataTables in hidden <div>s. This tables are works and sortable. When I insert this tables in other places of my page using .html() jQuery method (so I am dynamically copying HTML of each table to the other place) this tables becomes unsortable.
How can I force them to be sortable again?
Your initialization with .DataTable() has to be attached to something that is already on the page after the initial loading of the DOM elements.
Try $("body").find(".yourTable").DataTable() for initializing.
(If you have a more specific static container that contains all you DataTables at any point in time, replace body with that one for better performance.)
Don't use an ID if you end up having multiple elements with the same ID on the page, use a class instead. Otherwise the jQuery selector might only pick up the first occurrence.
Try with this:
var table = $('#yourTable');
table.clone().appendTo('#newParent');
table.remove();
The .clone() method, should clone all JS events with it.
(Be carefull, I removed the original table because you would have duplicated IDs, if its not the desired result you might need to change IDs with some JS)
.clone()

Removing a dynamically generated element

I have implemented a user-generated keyword list for a project I'm working on, using jQueryUI autocomplete to suggest existing keywords.
On selecting the autocomplete suggestion, the returned string is added to the html of a div, as a child div.
I would like to add a removal function whereby the user can remove the child div if erroneously entered.
I've tried multiple suggested answers from Stackoverflow and elsewhere, but can't seem to get it working.
I've created a fiddle containing the pertinent elements.
The most logical solution to me was:
$('.keyword-entry').click(function(e){
var id = $(this).closest('div').prop('id');
$('#'+id).remove();
}
Though it would appear this doesn't work.
Whilst a solution to the problem would be very much appreciated to save my dwindling supply of coffee from running out this evening, I would also appreciate a rundown as to why I'm going wrong.
Thanks in advance.
Event delegation.
It's basically that you're attempting to attach an event to an DOM element that doesn't exist in the DOM at the time of load. Rewrite the .click() handler too:
$(document).on('click', '.trashYes', function () {
$(this).remove();
});
Fiddle: http://jsfiddle.net/6bBU4/
What it's doing is that, it's attaching the .click() event to the document (The top most DOM element) will travel down to find any new .trashYes, thus successfully executing the .remove(). This doesn't have to be bound to the document but to any DOM element within the document as well at load.
No need to get the id and then try and find it again, just do this...
$('<div id="'+id+'" class="keyword-entry" style="z-index:0">'+ui.item.value+' <--I want to remove this</div>')
.appendTo($('#keyword-list'))
.click(function(e){
$(this).remove();
});
when adding the keyword entry

Fire ajax call on onclick and div

I am attempting to fire off an AJAX call based on the onclick event for a google map integration. The info_window_content function seen here: http://jsfiddle.net/6xw2y/ is the call to create the divs that reside within the map itself.
The "v" variable does in fact contain a store_id. So in the opening line of that function, it has the following:
var info_window_string = "<div class='maps_popup' id="+v.id+">";
Now I have an onclick event that I have duplicated and modified. The first onclick event works just fine and refreshes the panel as it should. The second onclick event doesn't work and the code for that is below:
$("#div").click(function(){
var store_id = $(this).find("div").attr("id");
var pathname = "ajax=1&store_id="+store_id+"&action=get_nearby_stores&distance="+distance+"&lat="+lat+"&lng="+lng+"&products="+$('#edit-products').val();
$("#pocp_content").load("file1.php?" + pathname);
});
That doesn't seem to work. I've also tried changing the div tag to be like this:
$("div").click(function(){
Which still doesn't work. As an added side hint. At one point I was able to get it to refresh but it was passing map-container as the store_id, instead of the id itself.
What am I missing here?
I agree with Joke_Sense10,
but I think you're probably not binding the event to the right DOM element.
Try to open up the developer console in your browser (while being on the side you develop this code for), and enter $("#div") to see if the element it returns is the one you expect. You can also use console.log($("#div")) in the code for that.
answer in comments
For a larger number of elements, always use .on() method as the latter will bind an single event listener on one of the topmost nodes in the DOM tree.
$(document).on("click","#"+v.id, function(){

How to make function work after append

For example i'm using append, and for example i'm appendig button in to a div, and i have function $('button_id').click(... etc to work affter i append the div, how can i do that.I mean i get no errors, but the function is not starting, it's because i append and then i want to use the function but how to do that, i tryed with delegate, but same thing.I tryed with function in the button tag , onmouseover and then the function thing, but nothing it gives me function not found.What is the solution ?
I have two events, one event is click event that appends button, the other event is click event that does something if the button that was appended is clicked, but that second event is not working ?
Try using :
$(elem).live(...)
It will bind event for now and in the future.
Firstly, it always helps if you show us the exact source code. $('button_id') is the incorrect selector to start with, try something more along the lines of $('#button_id') as your selector. Also, are you appending dynamic content? Anyways, I've always used the delegate() function quite successfully, but have you tried using the live() function? Also, one more thing to make sure of is that you have the newest version of jQuery as your source.
As was stated as well, you can not have duplicate ids, if you want to have a pointer, use class, instead of id="some_id" use class="appended". To select those using jQuery, use the selector like this $('.appended').
Try something like this it will work as per your expectations.
$("#button_id").click(function(){
//On click code goes here
}).appendTo($("#div_id"));
It's difficult to determine the problem you're having without seeing your code, but delegate (or live) should be perfect for what you're trying to do:
$("body").delegate("#b", "click", function() {
alert("ok");
});
$("#example").append('<input type="button" id="b" value="Click" />');
The click handler above will fire when an element with id="b" is clicked, whether or not that element happens to be in the DOM right now or not.
However, as others have noted, it's important to remember that IDs need to be unique within a document, so by the sounds of it you may be better of using classes instead.
You can see an example of the above code running here.

Categories

Resources