Sending additional information with JQuery remote form validation
I'm trying to remote validate a field by looking at two different fields. The issue is, in all the examples I see on how to do remote validate sending additional data, they're using the id of the other field that is being processed. So the example on the jQuery validate API page for remote() uses "#username" and sends that in addition to the email field.
My page is odd, and has multiple forms that are the same, and the number of forms on the page is variable, so I can't have a unique id for each field. Is there a way to find out which field or form is being validated/making the remote call? I tried something like the following, because I thought that $(this) would have been the text box being validated, or the individual form being validated, but that doesn't appear to be the case.
number: {
开发者_如何学Go required: true,
number: true,
remote: {
url: "confirm.php",
data: {
toy: function() {
return $('select[name="toy"]:selected',this).val();
}
}
}
}
Thanks, Jared
Edit: I ended up figuring out a way to get it working. The advice to pass the form along gave me the idea.
Since I had multiple forms on the page, I was using $('form').each(function() {$(this).validate({....})});
So I just saved a reference to the current form with var form = $(this) before the validate call, and then within the example I gave earlier I only had to make a small change:
data: {
toy: function() {
return $('select[name="toy"]',form).val();
}
}
And now each field knows which form it belongs to!
You could assign a unique formId
to each of the forms, and whenever the form is submitted, you could submit the formId
alongwith the other info from the form in order to identify which form is being submitted?
For example, in the html code of your form, you could do something like this:
Form # 1: (with form id as 1)
<form id="form_1">
Name: <input type='text' id='name_1'> <br>
Address: <input type='text' id='address_1'> <br>
<input type='button' value='Submit' onclick='validate(1);'>
</form>
Form # 2: (with form id as 2)
<form id="form_2">
Name: <input type='text' id='name_2'> <br>
Address: <input type='text' id='address_2'> <br>
<input type='button' value='Submit' onclick='validate(2);'>
</form>
In the javascript, something like this:
function validate(formId)
{
var data = {};
//Example data that is to be submitted for validation:
data.name = $("#name_" + formId).val();
data.address = $("#address_" + formId).val();
//.. and so on
data.formId = formId;
$.post('http://example.com/confirm.php', data, function(result)
{
//process the return of the remote validation here,
//found in the variable: result
}
);
}
精彩评论