Search code examples
javascriptjqueryurlkeypress

jQuery key press event only work in web address with # sign at the end


I got my first version of test website. Links here. You may notice on the right up corner there is a search box. If you just type a search query and click search, everything work. But if you just type a search query and press enter. It will just refresh the entire page.

FYI. You need to search available color name. Like blue or red.

However, if you click the search button first and then change query and press enter. This time it will work. You will notice the url has been added a # at the end of address.

The Js code show below. Or you can go to my page and check the resource.

$("#query").keyup(function(event){
    if(event.keyCode == 13){
      $("a#submit").click();
    }
  });

  $('a#submit').click(function(event) {
    var query = $('#query').val()
    var url = 

    $.getJSON(url, function(json, textStatus) {
      ...};
 ...};

This is a Bug or how I can solve it. Thank you.


Solution

  • Adding preventDefault to the form submit event will stop the page from reloading. Read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

    $('#formid').submit(function(event) { // Note that you'll need to give your form an id
        event.preventDefault();
    }
    

    You'll probably want both the onclick and submit events to call a function.