Results 1 to 2 of 2

Thread: Disable Submit Whilst Input Is Empty

  1. #1
    Join Date
    Jul 2007
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Disable Submit Whilst Input Is Empty

    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)
    Code:
    <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>

  2. #2
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by Pope Pius X2 View Post
    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:

    HTML Code:
    <form ... onsubmit="return validate(this);">
    Code:
    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.
    Mike

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •