0

I would like to know whether returning false on the keypress event is sufficient to prevent the keyup event, and whether this works for all browsers.

Consider the following code snippet:

$('#input1').keypress(function(event) {
 return true;
});

$('#input1').keyup(function(event) {
 var text = $(this).val();
  $('#output1').val(text);
});

$('#input2').keypress(function(event) {
 return false;
});

$('#input2').keyup(function(event) {
 var text = $(this).val();
  $('#output2').val(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h4>Test 1</h4>
Input: <input type="text" id="input1"/>
Output: <input type="text" id="output1"/>

<h4>Test 2</h4>
Input: <input type="text" id="input2"/>
Output: <input type="text" id="output2"/>

When you type into the input field for "Test 1", the corresponding output field reflects the changes. However, for "Test 2", the keypress event returns false, preventing the keyup event from occurring.

This works on Chrome, but does it work on all browsers, including IE? Is it a good way to achieve the demonstrated functionality?

ktm5124
  • 11,861
  • 21
  • 74
  • 119
  • @Taplar I tested it on Chrome but I'm curious about other browsers and whether I followed best practices. – ktm5124 Oct 19 '18 at 15:47
  • 1
    https://stackoverflow.com/questions/1639338/why-does-returning-false-in-the-keydown-callback-does-not-stop-the-button-click Hope this can answer your question – Squick Oct 19 '18 at 15:48
  • Best practices would be to be aware of what you are doing and what the side effects are. Returning false on an event handler effectively performs a preventDefault and a stopPropagation. If you want both of those things to happen, then returning false is appropriate. The debate beings at weither or not expliciting performing both those operations, rather than returning false, would be more readable and apparent to future programmers. Which would be a discussion you would want to have with your team and decide on. – Taplar Oct 19 '18 at 15:52
  • @Taplar My question was basically whether returning false performs a preventDefault and stopPropagation across all web browsers. Does it? – ktm5124 Oct 19 '18 at 16:01
  • Possible duplicate of [event.preventDefault() vs. return false](https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) – Taplar Oct 19 '18 at 16:09

0 Answers0