Search code examples
javascriptjquerykeyup

Trouble with jQuery keyup()


The page reloads instead of calling the click function, but if I insert a query string ?# after the .html extension, it works. Tested in chrome

My code:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>

        $(document).ready(function () {

            $('#search_btn').click(function () {
                alert("searching");
                // search functions

            });

            $("#search").keyup(function (event) {
                if (event.which == 13) {
                    alert("enter key pressed");
                    $("#search_btn").click();
                }
            });
        });

    </script>
</head>
<body>
    <form>
       <input type="text" id="search" />
       <button class="btn" type="button" id="search_btn">Search</button>
    </form>
</body>
</html>

Solution

  • Prevent specific FORM to be submitted, using e.g:

    $('form:has(#search)').on('submit', function(e){
        e.preventDefault();
    });
    

    -jsFiddle-