Preventing form submission when input field is empty

<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>

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


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

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

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.