ascii - Why is backspace allowed in my jQuery whether I filter it out or not? -


i've got jquery:

$(document).on("keypress", '[id*=float]', function (e) {      //only allow 1..9 (48..57), '.' (46), , backspace (8)     var k = e.which;     if (k === 8 || k === 46) return;     if (k < 48 || k > 57) { e.preventdefault(); } }); 

...working on html:

<input type="text" id="txtbxfloat"> </br> <input type="text" id="txtbxhopefloats"> </br> <input type="text" id="txtbxfloatingfreeasabird"> 

it can fiddled here

it comments say/what want. however, this:

$(document).on("keypress", '[id*=float]', function (e) {      //only allow 1..9 (48..57), '.' (46), , backspace (8)     var k = e.which;     if (k === 46) return;     if (k < 48 || k > 57) { e.preventdefault(); } }); 

iow, "8" (backspace) allowed in either case. why? guess it's not problem me @ moment, if wanted prevent backspace?

if want prevent backspace, should unbind default event , re-attach 'new' version of it.

try like:

$(document).unbind('keydown').bind('keydown', function (event) {     var doprevent = false;     if (event.keycode === 8) {         var d = event.srcelement || event.target;         if ((d.tagname.touppercase() === 'input' && (d.type.touppercase() === 'text' || d.type.touppercase() === 'password' || d.type.touppercase() === 'file')) || d.tagname.touppercase() === 'textarea') {             doprevent = d.readonly || d.disabled;         }         else {             doprevent = true;         }     }      if (doprevent) {         event.preventdefault();     }     // rest of code here }); 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -