Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept input entering

Is there a way to intercept the value the user inputs before it ever even appears in the element? I tried to use Object.defineProperty but it appears to not work for InputElement.value since

var value;
Object.defineProperty($('input')[0], 'value', {
    get: function() {return value},
    set: function(val) {console.log(val); value = val;}
});

doesn't appear to change any behavior. Or is oninput/onchange the only option? Since I'd rather have my code executes before the browser's.

http://jsfiddle.net/zpmu1xcu/

like image 322
Tahsis Claus Avatar asked Oct 25 '25 04:10

Tahsis Claus


1 Answers

If you want to detect input before the text is entered by the browser, you can use the Element.onkeydown property. This event fires as soon as the key is pressed down, before the browser interprets the action.

var demo_i = document.getElementById('demo_i');
var demo_d = document.getElementById('demo_d');

demo_i.onkeydown = function(e) {
    demo_d.textContent = e.which;
    // Returning false stops the event from going any further
    return false;
}
<input id="demo_i"><div id="demo_d"></div>