开发者

Quick jQuery Question

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?


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


if ($(this).find('#searchBox').val() == '') {
     return false;
    }


Add this to the function:

return false;

event.preventDefault() vs. return false


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...


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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜