Wrox Home  
Search P2P Archive for: Go

  Return to Index  

javascript thread: How do you make a required field in a form?


Message #1 by "Simon" <sjensen@P...> on Tue, 19 Dec 2000 00:03:50 -0000
I guess you'll have to use JavaScript for this.

Basically, you can take the following steps:

1. Put a normal button on your form. Don't use the input type="submit" 
because then browsers that have JavaScript disabled (or older browsers) can 
still submit the form.
2. Use the OnClick event of the button to call a function, like this:
         <input type="button" value="Save" id="btnSave" name="btnSave" 
OnClick="return checkInput();">
3. Then in the HEAD section (not mandatory, though) of your page, place the 
following JavaScript function:
<SCRIPT LANGUAGE="JavaScript">
function checkInput()
{
         if (document.yourFormName.txtYourField.value == "")
         {
                 alert("Please enter a value")
                 document.yourFormName.txtYourField.focus();
                 return false;
         }
         else
                 document.yourFormName.submit();
                 return true;
         }
}
</script>

Now when the user clicks the submit / save button, the JavaScript function 
is called. Only when the value of the text box is not "" the form is 
submitted. Otherwise, a messagebox is displayed informing the user what 
happened.

I have put the validation in a separate function. If you only want to check 
for "" then you could have placed the check inside the OnClick event. 
However, by putting it in a function, it's easier to expand your validation 
routine. You could for example call a (self made) Trim function in the 
checkInput to see how the input looks like without spaces around it 
("     " is usually considered empty too). Or check for a valid E-mail 
address etc etc.

HtH

Imar



At 12:03 AM 12/19/2000 +0000, you wrote:
>Hi,
>I was wondering how to make an input box a required field, so that the
>from can not be submitted until all of the fields have been filled out.
>Cheers,
>Simo'
>

--- 
NEED TECHNICAL TIPS, TOOLS, AND INSIGHTS?  Is FREE okay?
Visit EarthWeb for the latest in IT Management, Software Development, 
Web Development, Networking & Communications, and Hardware & Systems.  
Click on http://www.earthweb.com for FREE articles, tutorials,
and discussions from the experts.
---
You are currently subscribed to javascript as: $subst('Recip.EmailAddr')
To unsubscribe send a blank email to leave-javascript-$subst('Recip.MemberIDChar')@p2p.wrox.com

  Return to Index