Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing form submission when input field is empty

Tags:

When no value is provided to the roll input field an alert is produced by the empty() function but this empty value is still passed to retrive.php. So how can I stop this from happening and only pass the value to retrive.php when some input value is provided?

<html>
 <head>
   <title>STUDENT FORM</title>
    <script type="text/javascript">
        function empty()
        {
          var x;
          x = document.getElementById("roll-input").value;
          if (x == "") 
           { 
              alert("Enter a Valid Roll Number");
           };
        }
    </script>
</head>
 <body >
  <h1 align="center">student details</h1>       
    <div id="input">
      <form action='retrive.php' method='get'>
       <fieldset>
        <legend>Get Details</legend>
          <dl>
            <dt><label for="roll-input">Enter Roll Number</label></dt>
        <dd><input type="text" name="roll" id="roll-input"><dd>
            <input type="submit" value="submit" onClick="empty()" />
          </dl>
        </fieldset>
      </form>
    </div>  
  </body>
</html>
like image 410
Pawan Avatar asked Apr 11 '13 16:04

Pawan


People also ask

How do you prevent submit if form is empty?

If you're posting code, you need to precede it with a line containing only three backticks ``` and end it with a line contining only three backticks. Until someone uses it with JavaScript turned off!

How do I restrict a form submission?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.

How do I stop form button from submitting?

How do I stop a form from submitting in HTML? The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.


2 Answers

You need to return false to cancel the submit.

function empty() {
    var x;
    x = document.getElementById("roll-input").value;
    if (x == "") {
        alert("Enter a Valid Roll Number");
        return false;
    };
}

and

<input type="submit" value="submit" onClick="return empty()" />

jsFiddle example

like image 76
j08691 Avatar answered Sep 22 '22 15:09

j08691


How about using the required attribute?

<input id="Name" name="Name" class="form-control" placeholder="Enter name" type="text" required/>

Only works in html5 though.

like image 42
wecky Avatar answered Sep 23 '22 15:09

wecky