23

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>

6 Answers 6

44

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

0
22

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.

0
10

The easiest way is to add attribute "required" into the input tag

<input type="text" name="name" required>
0
2
<form method="post" name="loginForm" id ="loginForm" action="login.php">
<input type="text" name="uid" id="uid" />
<input type="password" name="pass"  id="pass" />
<input type="submit" class="button" value="Log In"/>
<script type="text/javascript">

$('#loginForm').submit(function() 
{
    if ($.trim($("#uid").val()) === "" || $.trim($("#pass").val()) === "") {
        alert('Please enter Username and Password.');
    return false;
    }
});

</script>
</form>
1

i use with this I thinking it's maybe can help

  $(function () {
        $('form').submit(function () {
            if ($('input').val() === "") {
                alert('Please enter Username and Password.');
                return false;
            }
        });
    })

or work with class or ID like this

$('.inputClass')
$('#inputID')
0

If you want to save code you can simply do:

<input type="text" name="roll" id="roll-input">
<input type="submit" value="submit" onClick="return document.getElementById('roll-input').value !=''"/>

I just say.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.