I have defined keyboard events which is working good in desktop but for touch devices not getting the onscreen keyboard event. I need to capture if user is typing. I have used the following segment of code :
$('#id').keydown(function(e){
//some code here
});
$('#id').keyup(function(e){
//some code here
})
I want the code defined in keydown
and keyup
to trigger even for touch devices (both tablets and mobiles). Please suggest how to capture the onscreen keyboard event and make the above code to run.
Have you tried using key press instead of key down
$("#id").keypress(function() {
});
Updated :
Due to android problems I now normally wrap my checks like this
if ($.browser.mozilla) {
$("#id").keypress (keyPress);
} else {
$("#id").keydown (keyPress);
}
function keyPress(e){
doSomething;
}
One way to solve this is by using
setInterval
whenkeyup
orkeydown
events are not detected.
var keyUpFired = false;
$('#input').on('keyup',function() {
keyUpFired = true;
// do something
});
if( keyUpFired === false) {
setInterval(function() {
if($('#input').val().length>0) {
// do something
}
},100);
}
Here is a small example using Materialize
in order to test in touch devices.
$(document).ready(function() {
var keyUpFired = false;
$('#input').on('keyup',function() {
keyUpFired = true;
if ($('#input').get(0).checkValidity() === true) {
$('label[for="input"]').attr('data-success','Custom Success Message: You typed...'+$(this).val());
} else {
$('label[for="input"]').attr('data-error','Custom Error Message: Username too small');
}
validate_field($('#input'));
});
if( keyUpFired == false) {
setInterval(function() {
if($('#input').val().length>0) {
if ($('#input').get(0).checkValidity() !== false) {
$('label[for="input"]').attr('data-success','Custom Success Message: You typed...'+$('#input').val());
} else {
$('label[for="input"]').attr('data-error','Custom Error Message: Username too small');
}
validate_field($('#input'));
}
},100);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css" rel="stylesheet"/>
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s12">
<input placeholder="5-20 characters..." id="input" pattern=".{5,20}" type="text" class="validate">
<label for="input" data-error="wrong" data-success="right">Username</label>
</div>
</div>
</form>
</div>
The last answer on this page works: How can I get jquery .val() AFTER keypress event? -
Basically discard the "keyup" and change to "input", something like: $(document).delegate('#q', 'input', function(e) { etc }
来源:https://stackoverflow.com/questions/9940829/how-to-capture-the-onscreen-keyboard-keydown-and-keyup-events-for-touch-devi