What i want to do is when a form is posted, the script loops through all inputs with a specific attribute, and if it’s empty, it marks it red and changes the text to “This field is required” for 2 seconds, then it changes back to the default text.
Each field has the title of the field as a value, until you click it, then it disappears. Like a placeholder.
What happens now is the script runs fine, but if i try to post the form during those two seconds when the error text is displayed, it submits. I have no idea why.
Here’s the code:
var isWorkingInputForm = false;
$(document).ready(function() {
var defFormInputBgColor = null;
// Warn user if required field is missing when posting form
$('form').submit(function(e) {
// Return is form is working
if(isWorkingInputForm) console.log('is working');
if(isWorkingInputForm) return false;
// Halt is true by default.
var halt = true;
// Start working. If form is submitted between the start and stop it'll be ignored.
isWorkingInputForm = true;
// Nope, it's not working, let's loop through all inputs
$('.formwrapper *[data-required="true"]').each(function(i, v) {
console.log('not working');
var val = $(this).val().trim();
var defVal = $(this)[0].defaultValue.trim();
var input = $(this);
// Store bg color if not already stored
if(!defFormInputBgColor) {
defFormInputBgColor = $(this).css('background-color');
}
// Check if it's empty (or equal to the default value (placeholder))
if( val == defVal || !val ) {
halt = true;
// Set red background
$(input).css({
'background-color': '#FFDDDE'
});
// Show error text
$(input).val('Det här fältet är obligatoriskt');
// Wait for two seconds, then show the default text again
setTimeout(function() {
$(input).val(defVal);
}, 2000);
} else {
halt = false;
$(input).css({
'background-color': defFormInputBgColor
});
}
});
isWorkingInputForm = false;
if(halt) {
// Form didn't validate, do nothing
e.preventDefault();
}
});
});
Pay attention to the isWorkingInputForm variable. As soon as the form is submitted, it is set to True, and at the bottom of the script it’s set to False again.
As you can see at the top of the script, i check if isWorkingInputForm is set to true (meaning it’s being paused for two seconds), and if is, return false (don’t continue).
For some reason, the form submits if i press the submit button while it’s paused. Any ideas why?
You are clearing the
isWorkingInputFormtoo soon. You are clearing it when the handler returns, which is way before two seconds. MoveisWorkingInputForm = falseinto the timeout: