View Full Version : Disable Submit Whilst Input Is Empty
Pope Pius X2
07-20-2007, 12:10 AM
I'm trying to make my submit button disabled whilst a certain input field is empty, and then when someone enters a value it becomes enabled again. I tried this but it didn't work. Any ideas? (Forgive me, I'm a Javascript noob)
<script language="javascript" type="text/javascript">
<!--
strfield1 = document.forms1.os1.value
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ')
{
document.form1.submit1.disabled=true;
}
else
{
document.form1.submit1.disabled=false;
}
-->
</script>
mwinter
07-20-2007, 07:19 PM
I'm trying to make my submit button disabled whilst a certain input field is empty, and then when someone enters a value it becomes enabled again.
First, a note: do not depend upon this. If something would break if a user submitted an empty value, fix that thing!
<script language="javascript" type="text/javascript">
<!--
The language attribute is deprecated and redundant in the presence of the type attribute. Attempting to "hide" scripts using markup comments is similarly out-dated.
Rather than trying to disable the submit button, cancel the submission:
<form ... onsubmit="return validate(this);">
function validate(form) {
var controls = form.elements;
if (isEmpty(controls.os1.value)) return false;
return true;
}
function isEmpty(value) {
return /\W/.test(value);
}
The only question is what you consider to be "empty". The isEmpty function above simply ensures that there's a non-white space character (letter, digit, punctuation, etc.) somewhere in the value of the control, but the test can be much more rigorous than that if you'd prefer.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.