I've written some JavaScript/jQuery code that adds a users email to my newsletter database. There is a "subscribe" button to start the process, but I also wanted the user to be able to hit return for usability.
Weirdly, the code works for both the button and when the return key is hit in that the email is added to the database, but the callback function which just displays an alert is only triggered when the button is hit, not when the return key has been pressed.
$('#newsletter_button').click(function(event) {
newsletterSignup();
});
$('#newsletter_email').bind('keyup', function(event) { newsReturn(event); });
function newsletterSignup() {
var email = $.trim($('#newsletter_email').val());
if(!validateEmail(email)) {
alert('Please enter a valid email');
return false;
} else {
// add email to database
$.post('newsletterSignup.php',
{ email: email },
function(data) {alert(data);}
);
$('#newsletter_email').val("");
}
}
function newsReturn(evt) {
if (evt.keyCode == 13) {
newsletterSignup();
}
}
The function has to work the same no matter how it's been called surely! Like I say the post function is obviously being called both times because the email is being added to the database.
The only thing I can think of is that it's something to do with events. Not sure what though.