Reputation: 2340
I cannot handle properly some events in input type="text". I just need a filter to only accept [^0-9] chars.
I need the following help:
What i tried so far:
keypress event i handle nicely any input from keyboard. (any chars not in [^0-9] and enter, backspace, home, end, etc will be simply ignored).
keyup i handle weirdly Control + Paste (keyboard) event. I paste some string, and after the string is pasted, i crop any non-white list chars. PS: BUT this don't work with Right Click + Paste (mouse), neither
onChange the garbage string stay visible until the user blur the field.
What i want:
Copy the example string "123.321.456-78" and paste "12332145678" or "abc!2¨#7" and paste "27".
Do not accept any non-white list chars from any possible way. (even with $('#field').val("trash input 123").
From all problems above, i can handle nicely or weirdly (aka: keuup) the input, but Right Click + Paste (mouse) NEVER trigger ANY EVENT so i can do the properly treatment.
I thought about doing Interval Check, but this is too ugly.
EDIT:
Code below
function soNumeroInteiro_keypressHandler(event)
{
var code = event.keyCode || event.which;
switch(code)
{
case 8: // backspace
case 37: // left
case 39: // right
case 9: // tab
case 46: // delete
case 35: // end
case 36: // home
return true;
break;
case 86: // control + A
case 97: // control + V
case 120: // control + X
if (event.ctrlKey) {
return true;
}
break;
}
var tecla = String.fromCharCode(code);
return tecla.match(/^\d$/) != null;
}
function soNumeroInteiro_keyupHandler(event)
{
event.currentTarget.value = event.currentTarget.value.replace(/[^0-9]/g, '');
}
Upvotes: 2
Views: 498
Reputation: 34168
Please see this question for the mouse click events: How to distinguish between left and right mouse click with jQuery
NOW you have the mouse click event, even the right click, you can then poll the content for a short bit (2 seconds?) to detect changes and handle the content validation. This way, you COULD choose to either accept valid or reject the content based on your business logic needs.
EDIT: Just to add a note, the onpaste event will not work correctly in that it will fire (in some test cases at least) prior to the content being pasted.
Example:
$('#pasteyMe').on('paste', function() {
$(this).val();// gets the content prior to the paste event
});
To work around this, you could set another event watcher such as change and then fire that:
$('#pasteyMe').on('click focus blur paste', function() {
var me = this;
window.setTimeout(function() {
$(me).trigger('change');
}, 1);
});
$('#pasteyMe').change(function() {
$('#resulty').text($(this).val());
});
See this in action here: http://jsfiddle.net/MarkSchultheiss/kQxAj/
Upvotes: 1