I guess your code would work, however, I have some suggestions:
I would have added a hidden login template to the DOM that you can
clone()
and re-use. Keeping the HTML inline in the javascript will start becoming troublesome when you want some more complex functionality and/or layout.You can't simply do
var username = $(".loginID").val();
. This will always get you the first element with classloginID
. You need to make use of thethis
pointer when dealing with multiple instances.Pass the
data
as an object literal. Changedata: "username=" + username + "&password=" + password
todata: { username: username, password: password }
.
Just my two cents.
var Loginbox = (function($){
function loginbox(){
this.$element = $('.logintemplate').clone()
.removeClass('logintemplate');
this.bindEvents();
}
loginbox.prototype = {
bindEvents: function(){
var that = this;
this.$element.find('.send').on('click', function(){
$.ajax({
url: '/echo/json',
type: 'POST',
data: {
username: that.$element.find('.username').val(),
password: that.$element.find('.password').val()
}
}).done(function(data){
console.log('done');
}).fail(function(){
console.log('fail');
});
});
}
};
return loginbox;
})(jQuery);
for(var i = 0; i < 4; i++){
var box = new Loginbox();
$('body').append(box.$element.show());
}