Skip to content
Advertisement

HTML button that’s submitting an empty field even though it shouldn’t be

Here’s the HTML button I’m working with:

JavaScript

When someone hits the button but the “Other” text field is blank, it’s supposed to not redirect and instead show an error message. Right now the error message displays, but only for a quick moment before it redirects anyway.

Here is my complete JavaScript code:

JavaScript

I’m not sure if something’s wrong with the code I put in the button or in the JavaScript.

Advertisement

Answer

Disable button by default

The button should be disabled by default, and should only be enabled when the expected input value is detected. It appears you already have a mechanism for this in your example, but you have some impediments to overcome first:

  1. button should be disabled by default. Do this in the HTML:
    <button disabled …>Continue To Payment</button>
  2. input‘s onchange handler should just call setValueOnTarget(), because this function already calls EnableButton(). In the HTML:
    <input onchange="setValueOnTarget(this);" … >
  3. Remove the call to redirectPage() from the button‘s onclick handler and move it into addValueToQueryString() after you have assigned a value to newSrc.
  4. Add a call to EnableButton() after you call displayError() in cases where you want to allow the user to modify the input and try again.

For example:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement