$(document).ready( function () { var formValid = true; //variable to determine if the form inputs are valid; used for custom errors $('.rowtotal input, .payamount input').change ( function () { if($('.rowtotal input').val() != $('.payamount input').val()) { formValid = false; showCustomError('.rowtotal', 'Total must equal Amount.'); } else { formValid = true; hideCustomError('.rowtotal'); } } ); $('input[type=submit]').click ( function(e) { if(!formValid) { e.preventDefault(); //stop the form from being submitted showCustomError('.rowtotal', 'Total must equal Amount.'); } else { hideCustomError('.rowtotal'); } } ); }); //Using the provided element selector and message, add an error message next to the field function showCustomError(elementSelector, errorMessage) { hideCustomError(elementSelector); //remove previous error $(elementSelector + ' input').addClass('custom-error'); $(elementSelector + ' input').focus(); $(elementSelector + ' input').parent().append('
'); } //Hide the custom error generated by the showCustomError function function hideCustomError(elementSelector) { $(elementSelector + ' input').removeClass('custom-error'); $(elementSelector + ' input').siblings('.custom-error-message').remove(); }