1

I have this code:

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

This submits my search form. I'm trying to keep it from submitting when empty. I know that'll be difficult to do inline, but when I tried to take the JS code out of the link, it ceases to work, even when the inline code calls a function outside of the link.

I was told to use this code:

$('#searchPost').submit(function(event) {
    if ($(this).find('#searchBox').val() == '') {
       event.preventDefault();
    }
});

But I'm not sure where to put it to make it work. Of course, inline, that code doesn't do what I want it to. I put that completely in the head of my document and it didn't change much either. Any help?

AKor
  • 7,970
  • 26
  • 79
  • 133

6 Answers6

3

You will need to wrap it in $(document).ready(function(){}); or short hand of $(function(){});

Mark Coleman
  • 39,942
  • 9
  • 80
  • 101
0
if ($(this).find('#searchBox').val() == '') {
     return false;
    }
Vivek Goel
  • 21,134
  • 28
  • 101
  • 178
0

Add this to the function:

return false;

event.preventDefault() vs. return false

Community
  • 1
  • 1
Mike Thomsen
  • 35,490
  • 10
  • 55
  • 80
0

I think you want to trap the $('#searchPost').click() event, not the submit() event.

Try trapping $.click(), then checking the val(), then conditionally executing $.submit().

Make sure $('#searchPost') exists too...

Fudgie
  • 414
  • 3
  • 12
0

Without seeing any of your code, I'd say a safe bet would be to place that code after the jQuery script and after the form.

sdleihssirhc
  • 41,071
  • 5
  • 52
  • 67
0

You should wrap it in a DOMready handler, this is the easiest way to do it with jQuery:

<script>
$(function() {
   $('#searchPost').submit(function(event) {
       if ($(this).find('#searchBox').val() == '') {
          event.preventDefault();
       }
   }); 
});
</script>
roryf
  • 28,846
  • 16
  • 79
  • 101