0

I have a text box that is being used as a search filter for a group of Isotope items.

I want a simple button that when clicked, clears the text entered into the text box BUT also then replicates the same as pressing 'Enter' on the keyboard. Currently just clearing the text does not register with the isotope sorting so I need it to replicate pressing 'Enter' after it has cleared the value.

$('#clear_input').click(function () {
$('#quicksearch').focus();
$('#quicksearch').val('');
// something here to replicate pressing enter inside #quicksearch

Any ideas?

braX
  • 11,506
  • 5
  • 20
  • 33
Scott Eldo
  • 473
  • 11
  • 28
  • create a new function, as function clearSeachtextBox(){$('#quicksearch').val(''); } and call it as individual function from inside your enter button click. or you can also use this function with your clear button – Neeraj Sharma Aug 28 '16 at 10:57
  • Check this question about how to create keyboard events: http://stackoverflow.com/questions/3276794/jquery-or-pure-js-simulate-enter-key-pressed-for-testing – Dario Aug 28 '16 at 10:58

1 Answers1

0

Try this: http://codepen.io/anon/pen/QEZaaV

$('#clear_input').click(function () {
  $('#quicksearch').focus();
  $('#quicksearch').val('');
  
  setTimeout(function() {
    var e = jQuery.Event("keypress");
    e.which = 13;
    e.keyCode = 13;
    $("#clear_input").trigger(e);
  }, 10);
});

$('#clear_input').on( "keypress", function(event) {
  if (event.which == 13 && !event.shiftKey) {
    event.preventDefault();
    alert('Enter key fired');
  }
});
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<input type="text" id="quicksearch">
<button type="button" id="clear_input">Search</button>

EDIT:

Updated so the input gets cleared before pressing enter.

busuu
  • 586
  • 9
  • 22
  • Thanks for this. It appears to fire the 'Enter' before clearing the input though. I need to clear the input, then fire Enter... – Scott Eldo Aug 28 '16 at 11:18
  • So close! It only works the first click. Any subsequent clicks do not fire Enter... – Scott Eldo Aug 28 '16 at 12:25
  • try to increase delay time from 10ms to 500ms, and play around with that value. Also, are you sure the enter key doesn't get fired at all? put the alert inside "on keypress" like in the example, and check if it gets triggered. – busuu Aug 28 '16 at 13:15