10

I have a form that relies on javascript to do all the client side form validation. The form is submitted via javascript if all the fields are correctly filled in as opposed to using a standard "submit" button:

<button name="button" type=button onclick="validateReqFields('mForm', 'username, password, compPassword, firstName, lastName');">Register</button>

document[formName].submit();

If the client has javascript disabled, all of the form validation is done server side (its actually performed again regardless but that doesn't really matter). The problem lies with using a button with a type of button instead of submit. It works perfect with javascript, but how do I get around this when javascript is not available? If I use a submit button along with the javascript then it submits the form with each button press and doesn't work properly.

ryandlf
  • 27,155
  • 37
  • 106
  • 162

4 Answers4

4

Change the type attribute to submit.

<button name="button" type="submit" ... />
alex
  • 479,566
  • 201
  • 878
  • 984
  • I can't do this because it does not allow my javascript to keep the page from submitting and thus renders my javascript useless because the page submits anyways and just uses the server side validation. – ryandlf Oct 17 '11 at 03:08
  • 2
    @ryandl: You should use `event.preventDefault()`. – alex Oct 17 '11 at 03:16
4

Use a submit button instead of the "button" button, and then have your validateReqFields function return false if the form is not valid.

Then take out the form submit from the validateReqFields if you like.

This way

  • If the form is valid, then the button click will bubble and the form will submit
  • If the form is invalid, then the javascript will cancel the button click
  • If javascript is disabled, then it will be submitted to the server as a fallback
Matt Tew
  • 1,581
  • 1
  • 9
  • 15
-1

Use the <noscript></noscript> tags to define a "normal" submit-button when javascript is disabled.

ott--
  • 5,642
  • 4
  • 24
  • 27
-1

You could maybe use the <noscript> tag and encapsulate the above code with the button type as submit. If the client has js, the code inside the noscript will be ignored.

vishakvkt
  • 864
  • 6
  • 7
  • So in the case that javascript is disabled and the page uses the noscript tags, won't I then have two buttons on the page? – ryandlf Oct 17 '11 at 03:07
  • 3
    If you are going to downvote the "use `noscript`" answers, at least explain why you think it's not useful. – alex Oct 17 '11 at 03:19