'Disable Typewatch binding when Enter key is pressed

I am using Typewatch jQuery plugin in one of the applications and I have the following code for submitting the form and calling an Ajax request.'

searchForm.on('submit', function(event) {
    if (event) {
        event.preventDefault();
    }
    if (search.data.searchRequest) {
        search.data.searchRequest.abort();
    }
    searchForm.addClass('is-loading');
    search.data['searchStart'] = 0;
    $('#js-postslist--searchpanel').empty();
    $('.js-searchpanel-results').removeClass('is-visible');
    var filterQuery = csUtils.methods.getFilterQuery(true, search.data.terms);
    search.data.searchRequest = search.methods.ajaxCloudSearch(filterQuery);
});

searchField.typeWatch({
    callback: function() {
        return searchForm.submit();
    },
    wait: 500,
    highlight: false
});

Here the issue is, when I press Enter(return) key, the form is getting submitted twice. It is going to the submit function two times as the form has default submit behavior on pressing the Enter key. I can't remove this as users will press the key once they enter the search term. I need to disable the Typewatch binding when Enter key is pressed so it will not submit the form two times.

How can I do this ?



Solution 1:[1]

You can intercept the keydown event on the input element. If its the enter key call preventDefault to stop the form from submitting. The callback will be fired immediately because TypeWatch triggers the callback on enter key.

searchField.on('keydown', function(e) {
    if (typeof e.keyCode !== 'undefined' && e.keyCode === 13) {
      e.preventDefault();
    }
  })
  .typeWatch({
    callback: function(value) { console.log(value); },
    wait: 500
  });

You can see a working example here: https://jsfiddle.net/tbg7a84k/18/ (try commenting out the preventDefault call and you'll see that it submits the form).

There may be some value in TypeWatch returning the reason the callback was triggered, perhaps the callback could send a reason: ENTER_KEY or ELAPSED then in the callback you could simply check if reason === 'ENTER_KEY' (pull request welcome).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Denny Ferrassoli