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
  • 8,550
  • 27
  • 82
  • 136

6 Answers6

3

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

Mark Coleman
  • 40,542
  • 9
  • 81
  • 101
0
if ($(this).find('#searchBox').val() == '') {
     return false;
    }
Vivek Goel
  • 22,942
  • 29
  • 114
  • 186
0

Add this to the function:

return false;

event.preventDefault() vs. return false

Community
  • 1
  • 1
Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
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
  • 413
  • 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
  • 42,000
  • 6
  • 53
  • 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
  • 29,592
  • 16
  • 81
  • 103