function event.preventDefault() not working in android chrome - android

Here is a simple example of the issue I am facing: jsfiddle .
You can not enter values into the text field on PC. The very same code does not work on android chrome. I am able to type anything into the field.
I am trying to prevent text being entered into a text box under a certain condition
Here is the function
function func(event, src){
if (condition){
alert(33);
event.preventDefault();
}
}
I have used it like this:
<input onkeydown="func(event, $(this))" />
The code works perfectly on windows ie and chrome. However on chrome in android, it shows an the alert 33 but it does not prevent text from being entered. I have tried event.stopPropagation(); and return false but the output is still the same(only shows the alert).
Note: I can not use $("input").keydown() because of some other features. So I can only use events via html .

You can try this approach:
HTML
<input id="pVal" />
JavaScript:
const inpt = getElementById('pVal')
inpt.addEventListener('textInput', evt => {
evt.preventDefault();
})
It works in Android Chrome

Related

Placeholder as "dd/mm/yyyy? on date input in phonegap not working on phone

I am using phonegap/cordova to make mobile app, I have an form where there is an input type="date" for picking date. I have used placeholder for setting text on the input type="date" which works perfectly on browser (desktop), but when I am viewing the same form on phone it doesn't works i.e. it shows blank instead of placeholder text.
Please help me how to display the placeholder of input type="date" in phone (android).
I have tried all the possible solutions, setting it as type="text" and making it as type="date" on focus and other stuffs. Please help
Thanks.
Krunal
input type="date" is not a good practice as it is not supported in all browser. it might not work in old phone.
I advice you to use this plugin https://github.com/VitaliiBlagodir/cordova-plugin-datepicker
after adding this plugin use following code in click/tap event of input tag
var options = {
date: new Date(),
mode: 'date',
androidTheme: 5
};
function onSuccess(date) {
alert("Selected date is "+date);
}
function onError(error) {
alert("you canceled the dialog.")
}
datePicker.show(options, onSuccess, onError);
have a look at plugin's Readme.md for more options.
you can use moment.js to show date as your desired format.

How to scroll in to focused textbox in android + phonegap?

I am using PhoneGap (Cordovar 2.5) and jQuery Mobile 1.3.0. On iOS, whenever I focus on a text box, the keyboard shows and push up the page, but on Android it doesn't. I have tried to use android:windowSoftInputMode="" but no success. Please help.
In any part of you app (js file, of course) pus this script:
if(/Android 4\.[0-3]/.test(navigator.appVersion)){
window.addEventListener("resize", function(){
if(document.activeElement.tagName=="INPUT"){
window.setTimeout(function(){
document.activeElement.scrollIntoViewIfNeeded();
},0);
}
})
}
The answer was in: Android does not correctly scroll on input focus if not body element

Placeholder text for an input type="number" does not show in webkit ICS

I have the following input field
<input type="number" id="zip-code" placeholder="Zip code" />
Placeholder is shown in normal browsers except android 4.0 and above and the width also get reduced compared to other fields.
What could be the error?
It's a known bug in the default Android Webkit browser. As per this QuirksMode page, you can see that many versions of Android suffer from this. Chrome for Android on the other hand, doesn't.
I've created a simple JavaScript shim (fix) for this. First, read this question How to display placeholder's text in HTML5's number-typed input, then if you still want to use a placeholder like that, checkout my solution gist.
TL;DR;
Leave your markup as you would expect;
<input type="number" placeholder="Enter some numbers" />
Then run either of these scripts after the page has loaded;
// jQuery version
$("input[type='number']").each(function(i, el) {
el.type = "text";
el.onfocus = function(){this.type="number";};
el.onblur = function(){this.type="text";};
});
// Stand-alone version
(function(){ var elms = document.querySelectorAll("input"), i=elms.length;
while(i--) {
var el=elms[i]; if(el.type=="number"])
el.type="text",
el.onfocus = function(){this.type="number";},
el.onblur = function(){this.type="text";};
}
})();
By using type = "tel' instead of type = "number" the placeholder is displayed and the numeric keyboard is opened on focus.
I had the same problem and my solution was setting the 'type' field as text. I think it happens because of the type property. Your placeholder text is not a number! If you have to force user to use only number format, you may use javascript plugins for this and i did it like that :)
try this:
<input type="text" pattern="[0-9]" id="zip-code" placeholder="Zip code">

Mobile Web - Disable long-touch/taphold text selection

I've seen/heard all about disabling text selection with the variations of user-select, but none of those are working for the problem I'm having. On Android (and I presume on iPhone), if you tap-and-hold on text, it highlights it and brings up little flags to drag and select text. I need to disable those (see image):
I've tried -webkit-touch-callout to no avail, and even tried things like $('body').on('select',function(e){e.preventDefault();return;}); to no avail. And the cheap tricks like ::selection:rgba(0,0,0,0); won't work either, as hiding these won't help - selection still happens and it disrupts the UI. Plus I'm guessing those flags would still be there.
Any thoughts would be great. Thanks!
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
-webkit-tap-highlight-color:rgba(0,0,0,0);
This will disable it for every browser going.
Reference:
jsFiddle Demo with Plugin
The above jsFiddle Demo I made uses a Plugin to allow you to prevent any block of text from being selected in Android or iOS devices (along with desktop browsers too).
It's easy to use and here is the sample markup once the jQuery plugin is installed.
Sample HTML:
<p class="notSelectable">This text is not selectable</p>
<p> This text is selectable</p>
Sample jQuery:
$(document).ready(function(){
$('.notSelectable').disableSelection();
});
Plugin code:
$.fn.extend({
disableSelection: function() {
this.each(function() {
this.onselectstart = function() {
return false;
};
this.unselectable = "on";
$(this).css('-moz-user-select', 'none');
$(this).css('-webkit-user-select', 'none');
});
return this;
}
});
Per your message comment: I still need to be able to trigger events (notably, touchstart, touchmove, and touchend) on the elements.
I would simply would use a wrapper that is not affected by this plugin, yet it's text-contents are protected using this plugin.
To allow interaction with a link in a block of text, you can use span tags for all but the link and add class name .notSelected for those span tags only, thus preserving selection and interaction of the anchors link.
Status Update: This updated jsFiddle confirms you concern that perhaps other functions may not work when text-selection is disabled. Shown in this updated jsFiddle is jQuery Click Event listener that will fire a Browser Alert for when the Bold Text is clicked on, even if that Bold Text is not text-selectable.
-webkit-user-select:none; wasn't supported on Android until 4.1 (sorry).

HTML: Why does Android browser show "Go" instead of "Next" in keyboard?

I have an HTML login form that contains following elements (in this order):
input type=text (user name input)
input type=password (password)
input type=submit (Login button)
Why does the Android browser show "Go" button in soft keyboard instead of "Next" button when the focus is in the text input? This causes user to fail to login very easily because after entering the user name, the user presses the bottom right button in the keyboard (usually the correct action) and the form will be submitted with an empty password, which obviously is not going to work. [This behavior would make sense in case my browser was set to remember passwords and the password manager would be able to fill in the password. However, this is not the case here as you can test yourself below.]
I'd like to have the input type text to have "Next" button and the input type password (the last input before the submit) to have the "Go" button.
An example of problematic form is at https://peda.net/:login (this form contains code to detect "Enter" key for the input and prevents submitting the form unless the last visible form input is focused).
Do you know a real fix for this issue? I know that if I were implementing native application, I'd use android:imeOptions="actionNext" (see How to change the Android softkey keyboard "Go" button to "Next"). However, in this case it's an HTML form and Android default browser.
The problem is visible with at least following configurations:
"Browser" system app running on Android 2.3.4 (Cyanogenmod 7)
"Browser" system app running on Android 4.2.2 (Cyanogenmod 10.1)
"Browser" system app running on Android 4.3.1 (Cyanogenmod 10.2 M1)
"Browser" system app (AOSP Browser) running on Android 4.4.2 (Cyanogenmod 11.0 M3)
"Browser" system app (AOSP Browser) running on Android 5.5.1 (Cyanogenmod 12.1) [has an arrow icon instead of word "Go"]
"Browser" system app (AOSP Browser) running on Android 6.0.1 (Cyanogenmod 13.0) [has an arrow icon instead of word "Go"]
To add to John's answer, Android always adds 'Go' to text inputs and always adds 'Next' to number inputs. I'd love to hear the person responsible for this choice explain their logic.
The softkeyboard design is just lousy in this respect, because every user I've tested with so far has thought the big blue button in the keyboard must be the button that takes you to the next form field and then at the last form field lets you submit the form.
iOS it's even worse in this respect, since they offer a 'Go' button with every form field and no way to tab through the fields. It's nice that Apple likes to make computers simple for people, but sometimes assuming that people like it simple can shade into presuming people are all idiots.
Sorry about that rant. I do have something constructive to offer:
If your last form field happens to be type=number, then there is a tiny hack that will work on Android as well as iOS: add an invisible text input to the form with onfocus="$('#thisForm').submit();". In Android this field will briefly flash into view: in iOS it wont. To make the Android situation more palatable, you can either set a value for the text input like "Closing this form", or you can set its width to 0, which will cause the form field to be not quite 0 width but still very small.
Horrible hack, but hey, blame it on the UI people at Google and Apple.
The Android Browser always displays Go for input fields because some forms on the web (especially search boxes) have no submit button, and can only be activated by pressing Enter (Go is equivalent to Enter).
Instead some versions of Android will show a tab key in the bottom right of the keyboard to facilitate navigating between form fields.
I don't think you can prevent either of these behaviours.
Two possible workarounds:
Use JavaScript to ignore submission of the login form until both inputs are non-blank:
<form name="loginForm" onsubmit="return document.loginForm.user.value != '' && document.loginForm.pass.value != ''">
<input type="text" name="user">
<input type="password" name="pass">
<input type="submit" value="Login">
</form>
The cleanest solution would be to set both inputs to be required using the new HTML5 required attribute - but the Android Browser doesn't support this yet. However a good approach would be to supplement the required attribute with a JavaScript fallback such as that described by CSSKarma.
This is the Chromium issue if you want to watch it: https://bugs.chromium.org/p/chromium/issues/detail?id=410785
Here is a workaround for Android that changes the "enter" in the user input so that it "tabs" to the password field (and doesn't submit the form):
http://jsbin.com/zakeza/1/quiet
<form action="?">
User <input type=text onkeypress=key(event)><br><br>
Password <input id=pw type=password><br><br>
<input type=submit>
</form>
<script>
function key(event) {
if (event.charCode == 13 && /Android/.test(navigator.userAgent)) {
event.preventDefault();
document.getElementById('pw').focus();
}
}
</script>
Edit: Note Windows Phone also puts Android into the UA, so needs testing that works on Windows Phone (and Android Firefox).
I was having this problem, and then I realized that I had forgot to wrap everything in a <form> element. That fixed everything.
see Replace Go button on soft keyboard with Next in Phonegap.
For a quick navigation see this plunker.
To follow complete code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<form action="" id="form">
First name: <input type="text" name="firstname">
Last name: <input type="text" name="lastname">
<select name="select" readonly="readonly">
<option>Select Something</option>
</select>
Last name: <input type="text" name="lastname" disabled="disabled">
Select <select name="select" id="selectBox">
<option>Select Something</option>
</select>
Last name: <input type="text" name="lastname">
Select <select name="select" readonly="readonly">
<option>Select Something</option>
</select>
<button type="submit">Submit</button>
</form>
<script>
(function($) {
$.fn.enterAsTab = function(options) {
var settings = $.extend({
'allowSubmit': false
}, options);
$(this).find('input, select, textarea, button').live("keydown", {localSettings: settings}, function(event) {
if (settings.allowSubmit) {
var type = $(this).attr("type");
if (type == "submit") {
return true;
}
}
if (event.keyCode == 13) {
var inputs = $(this).parents("form").eq(0).find(":input:visible:not(:disabled):not([readonly])");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
idx = -1;
} else {
inputs[idx + 1].focus(); // handles submit buttons
}
try {
inputs[idx + 1].select();
}
catch (err) {
}
return false;
}
});
return this;
};
})(jQuery);
$("#form").enterAsTab({ 'allowSubmit': true});
</script>
NOTE: don't forget to replace .live() method of jquery with .on() if using newer version of jquery than 1.9.
If you want the button to be 'Go' always use:
enterKeyHint="Go"
see this answer
https://stackoverflow.com/a/71593469/2721727
You can generically change ENTER keys into input elements into focussing the next input, using pure JavaScript.
It is not only useful in mobile browsers, but in desktop browsers too.
You can refine it for textarea and select.
function keyControls(e) {
// [enter] on inputs tranformed into focus next input.
// Sending events to inputs is security forbidden.
// We find the next element and focus() it.
// optionally restrict to certain user agens: && /Android/.test(navigator.userAgent)
if (e.key === "Enter") {
var el = document.activeElement;
if (el.tagName == "INPUT" || el.tagName == "SELECT") {
e.preventDefault();
var nextEl = null;
var found = false;
for (var i = 0, element; element = el.form.elements[i++];) {
if (element.type !== "hidden" && element.type !== "fieldset" ) {
if (found) {
nextEl = element;
console.log("found next element", element.name, " at ", i);
break;
}
if (el === element) {
console.log("found current element", element.name, " at ", i);
found = true;
}
// console.log("iterating form elements", element.name, " to ", i);
} else {
// console.log("iterating form elements - skipping ", element.name, " - ", i);
}
}
if (nextEl && nextEl.focus) nextEl.focus();
if (nextEl) {
console.log("key listener ENTER - transformed into TAB:", el.tagName, el.name, nextEl.tagName, nextEl.name );
} else {
console.log("key listener ENTER - transformed into TAB:", el.tagName, el.name, " next element not found" );
}
} else {
console.log("key listener ENTER on tagname:", el.tagName, el.name );
}
}
}
window.onload = function () {
document.addEventListener("keydown", keyControls, false);
console.log("key listener registered");
};
We can not prevent this default behavior because there is not input type="next" tag available in HTML as of now. So by default "Go" button appears. Below link having list of available input type tags: http://www.w3schools.com/tags/att_input_type.asp
To avoid confusion for user let GO button function as enter button only.
For this use a form tag but to avoid incomplete submissions use disabled attribute on submit button.
$("input:not(.submit)").bind('input',function(){
var isValid = validateInputs();
if(isValid)
{
$('.submit').removeAttr('disabled');
}
else
{
$('.submit').attr('disabled','disabled');
}
});
Now To avoid page reload dont use action or onsubmit attributes in form tag, instead use
$('#formid').submit(function(){
var disabled=$('.submit').attr('disabled');
if(disabled=='disabled')
{
return;
}
callOnSubmitFunction();
return false;
}
);
return false is important here to avoid page reload.
with the exception of chrome, the firefox and the default android browsers show a prev and next buttons which will work as tab buttons, so use proper tabindex atrributes on form input element.

Categories

Resources