Reputation: 13
I'm making a page with a div in the middle of it with an id of "devices_div," like so:
<div id="devices_div"></div>
When the page is loaded or when the form is submitted, the contents of resource_table.php are loaded into the div:
<script>
jQuery(document).ready(function()
{
jQuery("#devices_div").load("resource_table.php");
jQuery("#form").submit(function(event)
{
event.preventDefault();
var form = jQuery(this);
jQuery.ajax({
type: "POST",
data: form.serialize(),
url: form.attr("action"),
success: function(data)
{
jQuery("#devices_div").load("resource_table.php");
}
});
});
});
</script>
The contents of resource_table.php are:
<script>
jQuery("a#add_device").live('click', function()
{
jQuery("table#devices tr:last").after("<tr><td>Test</td><td>Test</td></tr>");
});
</script>
<table id="devices">
<tr>
<th>
Name
</th>
<th>
Xml Name
</th>
</tr>
</table>
<a id="add_device" href="#">Click here to add a device</a>
When I click the link with the id of "add_device" the first time, it adds a row to the table "devices" just fine.
Here's the problem: When I submit the form and click the link the second time, it adds two rows. If I submit the form and click the link a third time, it adds three rows, etc. So the jQuery function happens more than once. It should only happen once for each click. Any ideas?
Upvotes: 1
Views: 1249
Reputation: 708016
I would guess that it's because each time you do it, you're running this line of code again:
jQuery("a#add_device").live('click', function()
which adds a new copy of the event handler. So, you end up with multiple copies of the event handler each executing.
To solve that, you could either move that code to your main JS so it isn't part of the retrieved html or you could leave it in the retrieved HTML and protect it with a variable that keeps track of whether it's already been run or not.
Also, this selector "#add_device"
is more efficient than "a#add_device"
and will give you the same result as long as you aren't trying to avoid #add_device on something other than an <a>
tag. In general, there's no reason to put a tag type in front of an id. Ids are unique in the page. If you use only the ID, then jQuery can optimize the search with document.getElementById()
. If you put the tag type in front of it, it can't optimize as much.
Upvotes: 0
Reputation: 95062
you are binding the live event multiple times. try moving the live event to the parent page rather than the page that gets loaded multiple times.
Edit:
Another option is to modify the script block to use .bind
<script>
jQuery("a#add_device").bind('click', function()
{
jQuery("table#devices tr:last").after("<tr><td>Test</td><td>Test</td></tr>");
});
</script>
and then move it to the bottom of the file it is in, below
<a id="add_device" href="#">Click here to add a device</a>
Upvotes: 4