Search code examples
jqueryinputbox

Prevent refresh on enter. while in input box


Whenever input box is in focus, Enter results in page refresh. I want to prevent refresh on enter and put an event on it. Here's what i came up with, but this triggers Enter to refresh:

$(document).ready(function () {
$("#textboxid").on('keyup', function(e){
    if(e.keyCode === 13){
        $("#textboxid").animate({
        color: '#FFF'
    }, 2000, function () {
        $(this).val('').css('color', 'black');
    }); 
    }
});
});

Solution

  • use below code . add e.preventDefault(); when keyCode is 13

    you can check condition on keydown event . which fires when user press enter.

    $(document).ready(function () {
      $("#textboxid").on('keydown', function(e){
        if(e.which === 13){
          e.preventDefault();
          $("#textboxid").animate({
           color: '#FFF'
          }, 2000, function () {
           $(this).val('').css('color', 'black');
        }); 
       }
     });
    });
    

    Or use return false to prevent page refresh

    $(document).ready(function () {
      $("#textboxid").on('keydown', function(e){
        if( e.which === 13){
          $("#textboxid").animate({
           color: '#FFF'
          }, 2000, function () {
           $(this).val('').css('color', 'black');
        }); 
        return false;
       }
     });
    });