AKor
AKor

Reputation: 8882

Preventing a search field from submitting when empty using jQuery

I have a search box where I'm already using jQuery to submit the form, I just don't know how to keep it from submitting if the search box text field is empty. Any help?

Here's my code:

<a href="javascript:$('#searchPost').submit()">Search</a>

Upvotes: 0

Views: 1844

Answers (3)

TimFoolery
TimFoolery

Reputation: 1925

In a tag within the head:

function submitSearch() 
{
  if (document.FormName.SearchTextBoxName.value) $('#searchPost').submit();
}

Update the link:

<a href="javascript:submitSearch()">Search</a>

Upvotes: 0

Delan Azabani
Delan Azabani

Reputation: 81384

document.getElementById('searchPost').addEventListener('submit', function(e) {
    if (!document.getElementById('searchBoxID').value)
        e.preventDefault();
}, false);

Upvotes: 1

alex
alex

Reputation: 490183

$('#searchPost').submit(function(event) {

   if ($(this).find('input').val() == '') {
      event.preventDefault();
   }

});

Upvotes: 5

Related Questions