Kiran Patil
Kiran Patil

Reputation: 25

Validating required input before onlick submit redirect

I am writing the following HTML code which requires certain input values and has a submit button which redirects to a different site when clicked. Currently the Submit button redirects even if no value is entered into the input boxes. I want the submit button to only work if all the input values are filled.

<!DOCTYPE html>
<html>
<body>

<h3>Please enter the following information</h3>

<form>
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="" required><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="" required><br>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="email" value="" required><br>
  <label for="UserID">UserID:</label><br>
  <input type="text" id="UserID" name="UserID" value="" required><br>
  <label for="password">Password:</label><br>
  <input type="password" id="password" name="password" value="" required><br><br>
  <input onclick="window.location.href = 'https://example.site';" type="submit" value="Submit" />
  
</form>
</body>
</html>

Upvotes: 1

Views: 53

Answers (1)

Spectric
Spectric

Reputation: 31987

The reason is because your submit isn't properly structured.

You see, if you replace your input submit with a button, it works perfectly:

<!DOCTYPE html>
<html>
<body>

<h3>Please enter the following information</h3>

<form action="https://example.site">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="" required><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="" required><br>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="email" value="" required><br>
  <label for="UserID">UserID:</label><br>
  <input type="text" id="UserID" name="UserID" value="" required><br>
  <label for="password">Password:</label><br>
  <input type="password" id="password" name="password" value="" required><br><br>
  <button>Submit</button>
  
</form>
</body>
</html>

All you would have to change is add the link which you want it to redirect to in the action defined in the form.

This is the recommended method.

Keep in mind that you should always perform server-side checks regardless of whether there is a required attribute in the input field, as it can easily be removed.

Upvotes: 1

Related Questions