Reputation: 558
I have a form that submits an email address into my db and it works fine except if I wanna put more then one of them on a page. When I do that then it forces me to put the info in on what ever form is hirer up in the html. The code I have is the following:
$('#signup').submit(function() {
$('#response').html('Adding email address...');
$.ajax({
url: 'send.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#signupResponse').html(msg);
}
});
return false;
});
HTML:
<form id="signup" class="clear" action="" method="get">
<label for="mce-EMAIL">Get the latest Poster Facts!</label>
<input type="submit" value="Hit Me" class="signupButton" name="subscribe" id="mc-embedded-subscribe">
<input type="text" name="email" class="signupEmail" alt="Enter Email Address" />
</form>
<span id="signupResponse"></span>
Now for me the easiest way I can think of fixing this would be to put the same exact code but change #signup and #signupResponse to something else but I figure there has got to be a better way.
Thanks for the help
Upvotes: 0
Views: 482
Reputation: 431
Changing #signup and #signupResponse would work, and if you only have two forms, you could certainly do that.
If you want to make a generic version, you could do that with classes. Change #signup to .ajaxForm (or something like that). Depending upon where #signupresponse is, you can do something like .parent() or .children('.response') to refer to it. You can also use $(this) within the function to refer to the form that was selected, not all forms.
So for example, if your structure is
<div class="ajax-form">
<form>
...
<input type="text" name="email" class="email" />
<input type="submit" value="Submit" />
</form>
<span class="response"></span>
<span class="signup-response"></span>
</div>
You could do :
$('.ajax-form form').submit(function() {
$(this).parent().children('.response').html('Adding email address...');
$.ajax({
url: 'send.php',
data: 'ajax=true&email=' + escape($(this).children('.email').val()),
success: function(msg) {
$(this).parent().children('.signup-response').html(msg);
}
});
return false;
});
This generic format gives you one javascript for two forms.
Upvotes: 2