I am working with jQuery and after looking over other questions, I cannot seem to find an answer to the problem I have. I am trying to validate a form and submit it in one action. It work's fine it I use a submit button, but it I try and call the trigger from another function it fails.
jQuery code:
$(document).ready(function(){
$('#cmdSave').click(function (){
if ($('#age').val() != $('#agechk').val()) {
//Do something
}
else {
//Set form varaible
$('#frmactn').val('Save');
//Call form submit
$('#frmPrflDtls').submit();
}
});
$('#frmPrflDtls').submit(function() {
return vrfyDetails();
});
});
html:
<form name="frmPrflDtls" id="frmPrflDtls" method="get" action="details.php">
<input name="frmactn" id="frmactn" type="hidden" />
<input name="agechk" id="agechk" type="hidden" value="Senior" />
<input type="text" name="age" id="age" value="Senior" />
<input type="button" id="cmdSave" value="Save" />
</form>
So if I comment out the #cmdSave function and change the button type to submit all is well, but as it is, it will only validate false, or do nothing, but it never submits.
Thanks for any help.
-
Found solution to problem, there was an error in the vrfyDetails() function which caused a page refresh masking the error. So the actual code provided was ok.noangel– noangel2010年09月10日 14:28:18 +00:00Commented Sep 10, 2010 at 14:28
2 Answers 2
You should make the button type submit, and then add your specific code in the submit handler:
$('#frmPrflDtls').submit(function() {
if ($('#age').val() != $('#agechk').val()) {
//Do something
return false; // This will prevent the form submission
}
else {
//Set form variable
$('#frmactn').val('Save');
return vrfyDetails(); // This will allow the form submission
}
});
and your HTML:
<form name="frmPrflDtls" id="frmPrflDtls" method="get" action="details.php">
<input name="frmactn" id="frmactn" type="hidden" />
<input name="agechk" id="agechk" type="hidden" value="Senior" />
<input type="text" name="age" id="age" value="Senior" />
<input type="submit" id="cmdSave" value="Save" />
</form>
It is important to have a submit button so that users without JavaScript will still be able to submit the form. It's also important to also validate on the server, because users can circumvent JavaScript validation easily.
2 Comments
submit is a terrible idea.You should bind event to your form not button.
$(function(){
$("#frmPrflDtls").submit(function(){
if(form is ok){
return true; // this will post your form
}else{
return false; // form will not be posted
}
});
});