Search code examples
javascriptonchangekeypresskeydownpreventdefault

preventDefault() in a keydown event, onchange event not trigger


The preventDefault() called in a keydown or keypress event with value programmatically changed does not consider changing and does not trigger the onchange event at the exit of the input text.

Example code:

$('#textbox1').on('change', function() {
    alert('onchange called');
});

$('#textbox1').on('keydown', function(event) {
    if(event.key=='a') {

      $(this).val('A');
      //event.target.value = 'A';
      event.preventDefault();
    }
});

After a call of onchange (leaving the input text) digit only the char 'a' and leaving the input another time.

Fiddle code: http://jsfiddle.net/gxx5744s/1/

What does use the onchange event to check if a value has changed? A pair of old / new value variables? a boolean? Can be possible interact with it?

Keydown event default probably also does this.


Solution

  • Taking the idea of @Kaddath a revised solution a bit "dirty" but working might be. I do not like much but at the moment I did not find it better.

    $('#textbox1').on('change', function() {
    	alert('onchange called');
    });
        
    $('#textbox1').on('keydown', function(event) {    
      var oldValue = event.target.value;
      
      if (event.keyCode == 46) { //DELETE
      	event.target.value = ""
        } else
    		event.target.value = event.key + event.target.value;
        
      event.preventDefault();
    
      if (event.target.valueOnFocus === undefined) {
        // set a new property on the input element
        event.target.valueOnFocus = oldValue;
        
        $(event.target).on('focus', function(event) {
          // From the second time that enter on the input element,
          // update the new property
          event.target.valueOnFocus = event.target.value;
        });
        
       $(event.target).on('blur', function(event) {
          if (event.target.value !== event.target.valueOnFocus)
            $(event.target).trigger('change');
      	});
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="textbox1" />

    On fiddle: http://jsfiddle.net/gxx5744s/3/