Not all code paths return a value (JavaScript)

8.5k Views Asked by At
document.getElementById('search_field').onkeypress = function(e) {
        if (!e) e = window.event;
        var keyCode = e.keyCode || e.which;
        if (keyCode == '13') {
            window.location.href = '/search/?s=' + $('#search_field').val();
            return false;
        } 
    };

The last bracket show me an error, not all code paths return a value, what seems to be problem here ? Thanks

3

There are 3 best solutions below

4
Kristof On

End your function with return true.

If any other key then 13 is pressed the flow should just continue normally.

4
Manu On

Try this :

document.getElementById('search_field').onkeypress = function(e) {
  if (!e) {
    e = window.event;
  }
  var keyCode = e.keyCode || e.which;
  if (keyCode == '13') {
    window.location.href = '/search/?s=' + $('#search_field').val();
    return false;
  } 
  return true;
};

More... I think that you may not use both pure javascript and jquery

So you'd rather choose between

  • JAVASCRIPT :
      document.getElementById('search_field').onkeypress = function(e) {
            if (!e) e = window.event;
            var keyCode = e.keyCode || e.which;
            if (keyCode == '13') {
                window.location.href = '/search/?s=' + document.getElementById('search_field').value;
                return false;
            } 
          return true;
        };
    
  • JQUERY
      $( "#search_field" ).keypress(function( event ) {
        if ( event.which == 13 ) {
          event.preventDefault();
          window.location.href = '/search/?s=' + $(this).val();
          return false;
        }
        return true;
      });
    
0
Bergi On

Ignore your tool. Event handlers do not have to return a value in every occasion, it is fine if only a particular path does return false.