I have a problem with hiding keyboard in the iPhone simulator. My HTML code:
Instead of switching focus to another element you can simply blur your input like this:
$('#searchBar').blur();
It will hide the virtual keyboard.
Try adding another focusable element (ex: a <select>
) to your page (set its height to 0 so that its not visible yet focusable), and shift focus to that element before returning false.
The .blur()
method is probably the most effective one if you don't mind loosing the focus. But what if, e.g., you need it in order to keep a list of options open as it happens in a typeahead.
Bellow you can see the way I found to solve this problem.
$('#keepMeFocused').click(function() {
$(this).attr('type', 'text');
$('#hideKeyboard').removeAttr('disabled');
$('#msg').show();
});
$('#hideKeyboard').click(function() {
$('#keepMeFocused').attr('type', 'button').focus();
$('#hideKeyboard').attr('disabled', true);
});
#keepMeFocused {
box-sizing: border-box;
width: 200px;
height: 24px;
background: none;
border: solid 1px #ccc;
padding: 0 4px;
text-align: left;
}
#hideKeyboard {
height: 24px;
background: #666;
border: solid 1px #666;
border-radius: 2px;
color: #fff;
vertical-align: top;
}
#hideKeyboard[disabled] {
background: #ffffd;
border-color: #ffffd;
}
#keepMeFocused:not(:focus) ~ #msg {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="keepMeFocused" type="text">
<button id="hideKeyboard" disabled>Hide Keyboard</button>
<p id="msg">Keep me visible while input has focus</p>
UPDATE: I fixed a little bug in the code and simplified the JS a bit
Thank you Hosh Sadiq and techfoobar for helping me. Actually I did the following and it worked. It did not effect the css above or below this element.
$('.clr').after('<input type="checkbox" id="focusable" style="height:0; margin-left:-200px; clear: both;" />');
$('#focusable').focus();
Thanks once again. :)
I used regeint solution but modified a bit it doesn't work because i told phonegap to allow showing the keyboard without user interaction in Cordova.plist
i set KeyboardDisplayRequiresUserAction
to NO
function hideTheKeyBoard() {
$($.mobile.pageContainer).after('<input type="checkbox" id="focusable" style="height:0;margin-left:-200px;" />');
$('#focusable').focus();// maybe .blur() would work too.
$('#focusable').remove();
}
In jQuery, if you return false;
, it will stop the default browser behaviour, which, in this case, is both submitting the form as well as closing the keyboard. The following should work:
<form id="my_form">
<input type="search" id="searchBar" />
<div style="height:0;width:0;">
<input id="focusable" type="checkbox" />
</div>
</form>
jQuery:
$("#my_form").submit(function(){
one = $('#searchBar').val();
console.log(one);
doSearch(one);
$('#focusable').focus();
return false;
});