Search code examples
javascriptjqueryhrefkeypress

page is being refreshed instead of loading the assigned url


I'm trying to catch 'enter' key on an input textbox and then assign a new url to my page based on the input. The problem is that the link assigned to windoe.location.href is somehow being overwritten by the current value for windoe.location.href and the page is being refreshed instead of loading the new url assigned.

Here is the code:

  $(this).on('keydown', function(event) {
       myKeyCode=event.which
       if(myKeyCode==13) //'enter' key pressed
       {
          link=window.location.origin + '/search?search=' + $(this).val();
          window.location.href=link;
       }
  });

I'm guessing that some default behavior from keypress event is interfering. I have tried preventing the default behavior using event.preventDefault(); but that prevents the input textbox from taking any input.

Another weird observation: the code behaves just fine when I put an alert('something'); between the two lines inside my if-statement. It seems like the

window.location.origin + '/search?search=' + $(this).val();

is taking a while to be evaluated and using alert would give it enough time to evaluate.


Solution

  • if (myKeyCode==13) {
      event.preventDefault();
      link=window.location.origin + '/search?search=' + $(this).val();
      window.location.href=link;
    }