Form Stop Submit When Input is Empty - Javascript or Jquery

Form Stop Submit When Input is Empty - Javascript or Jquery

Prevent Form From Submitting If Form is Empty


Hello my name is Sitesh Biswal, I write article on developer queries. I find this query is as often asked. Hope i help even a single developer around the world


I have explained how this can be achieved in JavaScript and in Jquery.

1) Form Prevent Submitting Using JavaScript

2) Form Prevent Submitting Using Jquery


So Lets Go


First: Form Prevent Submitting Using JavaScript


Below is the HTML Form


<form method="post" enctype="multipart/form-data" action="this-is-my-form-link">

<input id="searchInput1" class="search-input" name="search_content" type="text">
<button type="submit" onClick="return empty()">Submit</button>

</form>




Below is the JavaScript Code


<script>

function empty() {

    var x;

    x = document.getElementById("searchInput1").value;

    if (x == "") {

        alert("Empty search");

        return false;

    };

}


</script>



This above JavaScript tested on my own project and working seamlessly on all browsers.


Second: Form Prevent Submitting Using Jquery


Below is the HTML form


<form method="post" enctype="multipart/form-data" action="index.php?route=product/searchad/search">

<input id="searchInput1" class="search-input" name="search_content" type="text">

<button type="submit" onClick="return empty()">Submit</button>

</form>



Below is the Jquery Code


<script>

function empty() {

var search_query = $('#searchInput1').val()';

if(empty(search_query)) {

alert('Search input is empty');

return false;

}

}


</script>


Dont forget to include jquery javascript link as below.


<script

  src="https://code.jquery.com/jquery-2.2.4.min.js"

  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="

  crossorigin="anonymous"></script>



Check my final result screenshots: 

Screenshot1:




Screenshot2:



Thanks for visiting my article page


Comments :

Add your valuable comments, so others can read.

Leave A Comment :