I have problem to add jQuery to some existing code, please help.
We have the same form (same form name, same fields, same submit button, no id or class defined for the form) appeared couple of times on a page, now I need to validation the form with jQuery, without passing in the form object, can jQuery tell which form was submitted?
Thanks everyone for your response, problem solved :-)
From your question's comments, it looks like you might need to specify the form's context along with your selector:
$('form').submit(function() {
var form = $(this);
var myInputValue = $("input[name='myinput']", form).val();
// myInputValue is now the value of the myinput control that is
// within the submitted form
});
Note that the jquery function takes an optional second argument that is the context of the selection. This should help you find input elements only within your submitted form.
Check the docs here:
http://api.jquery.com/jQuery/#expressioncontext
@NiftyDude's answer gets at the same issue, though he doesn't use jquery specifically to get the children of the currently submitting form.
It does not matter whether you have #id or .class attached to the <form>
tag in order to select it.
Try this:
$('form').submit(function () {
//put your ajax submission code here...
});
$("form[name='IDENTIFIER']")
This is useful if you have multiple forms on a single page to target a specific form
$('form').submit(function(e) {
// $(this) refers to the current form being submitted
// if you need to, for example iterate over all the inputs
var inputs = $(this)[0].getElementsByTagName('input'); // array of inputs
for(var i = 0; i < inputs.length; i++) { inputs[i].value; }
// this is important to avoid recursive submit
$(this)[0].submit();
return false;
});
$('form').submit(function(){
var form = $(this);
var inputs = $('input', this);
var isValid = true;
//do validation on the inputs of the form submitted.
if (isValid) {
//do something
}
return false;
});
Alternatively, you could catch the submit input action (that is what I like to do):
$('input[type="submit"]').click(function(event){
event.preventDefault();
var form = $(this).nearest('form');
var inputs = $('input', form).not(this);
var isValid = true;
//validate inputs
if (isValid) form.submit();
});
Note that the isValid = true
may not be needed depending on your code. It can be set to false if any of your elements fails validation and the form submit will not proceed. If you are using a validation library that does this for you and submits the form if valid, it will not be needed.
Some validators set an invalid class on each item that fails and you can just check for the presence of inputs in the form that have that class to determine if the form should be submitted.
isValid
is just a flag that you will set when you determine that the input fields are in a valid state, hence the //do validation on the inputs...
comment - Chris Farmer 2012-04-04 17:29