Forum Moderators: open

Message Too Old, No Replies

Button to check validation and redirect

         

falcon212

10:11 am on Nov 2, 2009 (gmt 0)

10+ Year Member



sounds simple but i cant figure it out

I have one form box that must be fill in, when clicking teh button if the box is not filled, it will popup message like "required to fill" and after hit enter/click the button, it redirect to a certain website

can someone help me on this ?

its for design and intraction purposes

Thanks

dreamcatcher

3:36 pm on Nov 2, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A warm welcome to WebmasterWorld. :)

Use window.location if it passes validation.

<input type="text" id="box" name="box" value="" />

if (document.getElementById('box').value=='') {
alert('Error');
return false;
} else {
window.location = 'http://www.example.com';
}

dc

rocknbil

4:26 pm on Nov 2, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



^^ The key there, and what draws me to answer, is the return false in D.C.'s solution, and this:

after hit enter/click the button

Most assume the button will always be used, but if it isn't - as in, hit the enter key - the event handler must be on the form, not the button. Otherwise it will submit without validating.

Wrong (it will "work" unless enter key is pressed):
<input type="button" onClick="return yourValidate();" Value="Submit">

Also wrong:

<input type="submit" onClick="return yourValidate();" Value="Submit">

The first is not going to work if JS is disabled, input type="button" has no inherent action. The second will work fine if the button is clicked, allowing the return false of the function to cancel the natural action of the form so you don't get two submits (one from JS, one from the form.)

The ideal situation is to put the handler on the form itself:

<form action="redirect-script" onSubmit="return yourValidate();">

In either case, the return false allows the JS to manage the submit and "cancels" the natural action of the form, submitting it only once. If Javascript is disabled, it will still submit the form. So . . .

You only have one more task - if Javascript is disabled, duplicate your Javascript actions in "redirect-script" above, a small script to capture the form values and redirect server-side. Then it will work both with and without Javascript. In the case of an error (blank field,) you would want to have "redirect-script" output the form again with the error at the top. Don't output "error, field is required" and suggest to navigate back. It's lazy and for most users, annoying.