catandmouse catandmouse - 5 months ago 10
Javascript Question

How to handle 2 same forms in one page?

I have two input fields and two submit forms in a page and they do the same thing... just to get the email of the user for subscription.

I am using the following code: http://codepen.io/anon/pen/KrqrYB

$("input[type='text']").focus(function() {
$(this).val('');
});

$(".message-validator").hide();

function validate() {
var email = $(".input-set-input").val(),
lastChar = email.substr(-1);
if (validateEmail(email)) {
$(".message-validator").hide();
} else {
$(".message-validator").show();

if (email === "") {
$(".message-validator").text("Please provide a valid email.");
} else {
if (email.indexOf('@') > 0) {
if (lastChar === "@") {
$(".message-validator").text("Please enter a part following '@'.");
} else {
$(".message-validator").text("Please provide a valid email.");
}
} else {
$(".message-validator").text("Please include an '@' in the email address.");
}
}

}
return false;
}

$("form").bind("submit", validate);

function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}


Is this a correct way to do it? Or should I create 2 different form classes and buttons and handle them differently?

Answer

Within the form submit handler function this will be the form the event occurred on.

So target only the elements that are in that form by using find()

Here's a small example as I don't plan to rewrite the whole thing

function validate() {
  var $form = $(this);// cache $(this) 
  var email = $form.find(".input-set-input").val()
   ......
 $form.find(".message-validator").hide();