简体   繁体   中英

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>

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

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

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

In a tag within the head:

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

Update the link:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM