1
votes

I have simple form to add an item into database built with PHP. I use html attribute Required like this :

<input type="text" name="iditem" required/>

To prevent submit button in sending blank value into database.

I also have javascript "onClick" on the submit button like this :

<input type="submit" onClick="return confirm('Add this item?')" />

What I want to ask is... How to make required attribute can be executed first before the submit button ?

Thanks guys...

3

3 Answers

0
votes

You can use "onsubmit" parameter in <form> and avoid the "onclick" on submit button:

<form action="test2.php" onsubmit="return confirm('Add this item?')" >
  <input type="text" required />
  <input type="submit" />
</form>
0
votes

<!DOCTYPE html>
<html>
<body>

<form action="">
  Username: <input type="text" name="usrname" required>
  <input type="submit">
</form>

</body>
</html>
0
votes

A simple approach here is to use plain JavaScript to do all the heavy lifting. Let's take a quick look.

First we set out HTML form

<!DOCTYPE html>
<html>
<body>

<form action="/" method="post" onsubmit="return validateForm();">
  Username: <input id="username" type="text" name="username">
  <input type="submit">
</form>

</body>
</html>

Now, pay attention to the form directive which mentions method, action and onsubmit. Let's go over all of those part by part.

I am sure you are completely aware as to what method and action do, but for the onsubmit part, it's linked to a JavaScript function called validateForm() which is defined as below:

function validateForm() {
  var username = document.getElementById( 'username' ).value;
  if( !username ) {
    return false;
  } 

  return true;
}

This function gets the value of the username element in the form and returns false if it's empty, and true otherwise. What this does is that it tells the event triggers to go forward with submitting the form to action using the method verb if the resultant value was true; if it was false, however, it just stops the execution. Much like we use the return keyword to break the current control.

So, in a way, it's triggered before your onClick handler. IN a very subtle way in the sense that it will not let the form get posted if the validation fails.

Now, of course, you can edit it to suit your needs by just adding a confirm dialogue as it'll return true if OK or YES is pressed and false otherwise. But this should give you a good example as to what all you can with the onsubmit attribute in particular, and the event attributes in general.

I hope this answers your question! You can find a fiddle here.