Search code examples
javascriptjqueryhtmlkeyup

If e.keyCode is the "enter" button and the element contains other text the condition is verified


I use keyup() method on input element:

i would like to know if is possible to do that the button pressed is enter but the input field is not empty then alert a variable. I tried:

$('#search').keyup(function(e) { //#search is id input
  if (($('#search').val() != "") && (e.keyCode == 13)) {
    alert($('#search').val());   //alert
    $(this).closest('form').submit();
  }
});

Doesn't work... because the condition is true also if the input element is empty :/

This is jsfiddle if you want help me: https://jsfiddle.net/0br6q72r/

Sorry for my english and thanks a lot! :)


Solution

  • You have to use keydown event instead and the values should have to be .trim()ed the values if it contains whitespaces:

    $('#search').keydown(function(e) {
      if (this.value.trim().length == 0 && e.keyCode == 13) { // <--ensures if no values entered and hit enter key
        e.preventDefault(); // then stop the process
      } else if (e.keyCode == 13) { // check if key is enter, it is required
                                    // as it enable user to put search inputs.
        alert($('#search').val()); // then alert the value
        $(this).closest('form').submit(); // and submit the form
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action='http://www.google.com' accept-charset="UTF-8" method="get" target='_blank' id='cse-search-box'>
      <input type='text' id="search" name='q' size='50' />
    </form>

    Fiddle.