Forum Moderators: open

Message Too Old, No Replies

validate form and then disable submit button

         

nevdev

3:07 pm on Sep 16, 2007 (gmt 0)

10+ Year Member



Question for you javascript gurus out there.

I've set my form so that, once data is entered in the various inputs, when the user clicks the "submit" button, that button is deactivated, to stop them clicking twice.

I do this by just putting:

onClick="this.disabled=true; this.value='Saving...'; this.form.submit();"

...after the value of the submit button. Seems to work fine on all browsers.

Trouble is, I'd like to do some js client-side validation of a text input field, disallowing certain characters. If I put this in as well as the above, the user won't be able to send the form after correcting mistakes, because the submit button will have been disabled.

Is there any way I can keep the "button disabling" feature, but also have the js character validation? (ie, user will be alerted upon any errors, and can then correct, and then click the submit button, which will *only then* disable itself)?

rocknbil

5:40 pm on Sep 16, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Move the disabling and form submit into your validation function.

<form method="post" action="" onSubmit="return checkForm(this);">
<inpt type="submit" id="mySubmit" value="Submit">
</form>


function checkForm(form) {
var msg ='';
// put your error checks here.
// If there is an error, msg will be populated,
// otherwise it will still be ''; So . . .

if (msg!= '') { alert(msg); }
else {
document.getElementById('mySubmit').value='Saving';
document.getElementById('mySubmit').disabled=true;
form.submit();
}
return false; // Return false prevents it from
// submitting in the event of error
}

When you pass "this" from the form itself, the function uses the variable form to reference the form object.

However, if Javascript is disabled, or the user uses their back button, you still have a problem (duplicate submit or a disabled button). For this reason, it's a good idea to do something server-side to avoid duplicate data - like check all fields for duplicate content, or output a unique identifier in a hidden field in the form so when it gets entered the first time it doesn't get entered a second (or just updated on the second.)

nevdev

8:13 pm on Sep 16, 2007 (gmt 0)

10+ Year Member



Thank you! All the server-side stuff is done - the receiving script redirects via a header - I was just trying to make it easier with some client-side js as well - but my js isn't as good as my php!

Many thanks again!