Reputation: 4353
I have a login form in which there are two links of Add member
and Reset password
. I also used jQuery Ajax to update the corresponding div's. I am working on Google App Engine and Python. The codes are as follows:
base.html:
...
<div id="loginDiv">{% include "login.html" %}</div>
...
login.html:
<a href="/login?arg1=resetPassword" class="resetPassword">Reset Password</a>
<a href="/addMember" class="addMember">Add member</a>
$(document).ready(function() {
// Add member
$('body').on('click', 'a.addMember', function() {
var url = $(this).attr('href');
$('#content').load(url);
return false;
});
// Reset password
$('body').on('click', 'a.resetPassword', function() {
var url = $(this).attr('href');
$('#loginDiv').load(url);
return false;
});
});
The problem is: when I click one of the buttons, multiple events will be triggered. Does the problem come from my wrong usage of jQuery's $('body')
?
Upvotes: 1
Views: 2092
Reputation: 22817
I advise you to DRY your code like this:
HTML:
<a href="/login?arg1=resetPassword" class="loadLink" data-target="#loginDiv">Reset Password</a>
<a href="/addMember" class="loadLink" data-target="#content">Add member</a>
jQuery:
$(function() {
$('body').on('click', 'a.loadLink', function(e) {
e.preventDefault();
var $this = $(this);
$( $this.data('target') ).load($this.attr('href'));
return false;
});
});
You use a single class, then rely on the data-target
attribute to tell js where to load href content.
Upvotes: 1
Reputation: 5989
Use following code
$("a.resetPassword").click(function(){
// Write your logic here
});
$("a.addMember").click(function(){
// Write your logic here
});
Upvotes: 1
Reputation: 2806
Make sure you are not running that javascript code more than once, if the code is being loaded through ajax that will happen.
A quick fix would be to do something like:
$('body').off('click','a.resetPassword');
$('body').on('click', 'a.resetPassword', function() { ...
Upvotes: 1