How to disable 'Paste' in Android browser using JQuery? - javascript

I have an input field which I do not want users to paste any values in it. I am using the following jQuery code and it works fine on desktop Browser and iPhone Safari. The problem is it's not working on Android browser.
$('#no_paste').bind("paste", function(e) {
e.preventDefault();
});
Here's the fiddle

I've tested this on Galaxy SIII and Android browser doesn't seem to send the
paste event. However, it still sends the input event after something was pasted.
If user is typing into a field he will fire one input event for each letter. However, if he is pasting, input event will fire only once for the whole string that was pasted. Basing on this observation we can block pasting like this:
$('#ie').bind("input", function() {
var previousValue = $(this).data('old_value') || '',
newValue = $(this).val();
if((newValue.length - previousValue.length) > 1) {
$(this).val(previousValue);
}
$(this).data('old_value', $(this).val());
});
You will find JSFiddle here.
Please note that this will also block autocomplete and all other strange input techniques that work in a similar fashion (I don't know about any).

Related

Is it possible to get selectionchange-like events for an input box in Firefox?

How can I get the selected text inside an input box in Firefox?
This is apparently a fundamental difference in the way that JavaScript works between Chrome and Firefox. To reproduce:
Navigate to www.google.com
Open JS console
Type following line: document.addEventListener("selectionchange", () => console.log(document.getSelection().toString()))
Type "text" into Google search box and do not hit enter
Use the mouse to select different portions of the "text" in the search box
In Chrome, you will see the event raised for selected text within the input element. This is consistent across various web pages that use input fields. In Firefox, the event is raised for selections outside the input, but when the text in the box is selected, no event is raised.
I have not found any explicit reference to this difference in any Mozilla documentation, nor have I found mention of it on any other web page.
Related but different question
Firefox Web Extension “selectionchange” is an older question, and the dom.select_events.enabled config attribute is now defaulted to true in FF 56. There is a second config attribute, dom.select_events.textcontrols.enabled that seems like what I'm looking for, but changing that value to true doesn't seem to have any effect.
Additional info (Edit 1)
Apparently there isn't even a way to get selected text in a textbox in FF? The following code also doesn't work:
setInterval(() => console.log(document.getSelection().toString()), 1000)
In FF, this will never return the selected text in an input field. In Chrome, it will.
Is this just a feature gap in FF? Is there no other way to extract selected text from a form field?
For me, setting dom.select_events.textcontrols.enabled in firefox did not enable document.addEventListener("selectionchange"... events for within textarea changes, but what it enabled was <textarea onselectionchange="...">.
By adding your handler to both, and toggling that firefox flag, you should get something that works in Chrome, Safari, and Edge (through document selectionchange) and in Firefox (through textarea onselectionchange).
I wasn't able to detect document.onselectionchange events from inputs or textareas in Firefox (86), but I am able to detect select events from the textareas themselves (onselect).
(Thanks to this post [in Russian] for the answer)
Based on this answer I have been able to create the following:
window.addEventListener('mouseup', function () {
selection = getSelectedText();
});
function getSelectedText() {
let elem = document.activeElement;
let elemType = elem ? elem.tagName.toLowerCase() : 'none';
if (elemType === 'input' || elemType === 'textarea') {
return elem.value.substr(elem.selectionStart, elem.selectionEnd - elem.selectionStart);
}
if (window.getSelection) {
return window.getSelection().toString();
}
if (document.selection && document.selection.type !== 'Control') {
return document.selection.createRange().text;
}
return '';
}
My testing so far shows that this seems to work well for both Chrome and Firefox.

ng-blur don't fire event on firefox with input number

I am trying to use ng-blur with an html input (type=number) element on firefox.
The problem I found is that when using the up and down arrows of the input number neither the blur nor the focus events are fired with firefox whereas with chrome works fine.
You can reproduce the issue in http://jsfiddle.net/chonw54e/
<div ng-app ng-init="focus=false;blur=false;active=false">
<input type="number" ng-class="{ myFocus: focus, myBlur: blur }" ng-focus="focus=true;blur=false;" ng-blur="blur=true;focus=false;">
<p>focus: {{focus}}</p>
<p>blur: {{blur}} </p>
</div>
Just load the page (with both firefox and chrome) and click on the up/down arrows of the html input number
input number
What am I doing wrong?
Thanks for the help!
EDIT: 11/12/2015
#Arg0n's solution fix the problem. However, it looks like a problem of either firefox or angularjs.
I have just created an issue on angular github here
It is not an angular problem. It is due to the firefox's event behaviour which don't focus the input when clicking the arrows inside the input (which in my opinion is a mistake).
EDIT: 14/12/2015
Firefox Issue created in bugzilla: https://bugzilla.mozilla.org/show_bug.cgi?id=1232233
You can fix this with jQuery, see this fiddle:
JavaScript
$(function(){
$("input[type='number']").on("click", function(){
$(this).focus();
});
});
Without jQuery, see this:
JavaScript
document.onreadystatechange = function() {
if (document.readyState == "complete") {
var inputs = document.querySelectorAll('[type="number"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = function() {
this.focus();
}
}
}
}
This will force the browser to focus on the input when it's clicked. (Input with type set to number).
A simple onclick="this.focus();" will work as nicely and much simpler if you have one field or using Angularjs's ng-repeat.

Fire event with right mouse click and Paste

I want to fire an event in a textarea immediately after paste some text inside the textarea. I can do that when Shift+Ins is used; however, I cannot do it when right mouse button and then paste (from the drop down menu) is chosen. Keyup fires after Shift+Ins. None of the rest fires when Paste is chosen after right mouse button clicking... What do I have to do?
<textarea name="message" id="message"></textarea>
$("#message").on('keyup contextmenu', function(event) {
alert("ok");
});
http://jsfiddle.net/f29vuwoL/7/
Thank you
Most browsers support the input event, which is fired when something is pasted or otherwise added, regardless of how:
$("#message").on('keyup contextmenu input', function(event) {
alert("ok");
});
Updated Fiddle
Note that using input is the most general method, firing when the control gets input regardless of how, and so if you hook multiple events (as above), you'll get multiple calls for the same input. For instance, if you hook both keyup and input, on browsers that support input, you'll get two calls. Similarly for paste and input when the user pastes, on browsers that support both.
If you need to support browsers that don't have either input or paste, I'm afraid the unfortunate answer is that you need to poll. Still, polling every (say) 250ms isn't asking the browser to do that much work, and you can feature-detect whether it's necessary:
var message = $("#message");
var events = null;
var previous;
if ('oninput' in message[0]) {
// Browser supports input event
events = "input";
} else if ('onpaste' in message[0]) {
// Browser supports paste event
events = "paste keyup contextmenu";
}
if (!events) {
// Ugh, poll and fire our own
events = "pseudoinput";
previous = message.val();
setInterval(function() {
var current = message.val();
if (current != previous) {
previous = current;
message.trigger(events);
}
}, 250);
}
console.log("Using: " + events);
message.on(events, function(e) {
console.log("Got event: " + e.type);
});
Updated Fiddle
You should use input event callback. See the demo here
You can use the dedicated paste event:
$("#message").on('paste', function(event) {
alert("ok");
});
Updated jsFiddle
However you might want to check browser support - I don't think jQuery normalizes this event.
If you need IE support, it might be a little more difficult, but it depends on your requirements - does it absolutely need to be a paste action? If not, TJ Crowder's answer is the way to go.
The on input is useful if you want to detect when the contents of a textarea, input:text, input:password or input:search element have changed, because the onchange event on these elements fires when the element loses focus, not immediately after the modification.The oninput event is supported in Internet Explorer from version 9.
$("#message").on('input propertychange', function() {
console.log($(this).val());
});
Fiddle

iPhone 6 / iOS 8.1.2 - Setting input type='date' with JavaScript gets wrong Keyboard

I wanted to have a placeholder on my date input, <input type="date" id="birthday"> however due to the W3C spec we can't do this so, I have amended my item to a text input <input type="date" id="birthday"> and on focus I change the input type to date.
$(document.body).on('focus', '#birthday', function (event) {
event.preventDefault();
if($(this).attr('type') !== 'date') {
$(this).attr('type','date');
}
});
This is fine in the desktop browser (where supported), on Android, iPhone 4 and other devices however on the iPhone 6 when the input has focus we still get the text keyboard and not the date selector keyboard for the input. Does anyone have any ideas of how I can get the correct keyboard to be shown?
I know it may be better to use or write a JS datepicker but I would like to use the native HTML5 date input. When the item loses focus and I click back on it the correct keyboard is shown. I tried to include code so when we gain the focus, we create a blur event then reintroduce the focus or a click event but this doesn't seem to work (see below). Has anyone had this problem before?
$(document.body).on('focus', '#birthday', function (event) {
event.preventDefault();
// this doesn't work
if($(this).attr('type') !== 'date') {
$(this).attr('type','date');
$(this).blur();
// perhaps this should be in a callback?
$(this).click();
}
});

e.preventDefault() & return false not working in firefox

Chrome :
Following code is working in Chrome.
$('.links').click(function(e) {
if(e.which == 2) {
console.log(e.which); // prints 2
//e.preventDefault();
//e.stopPropagation();
return false;
}
});
Firefox :
Since above code doesn't catch middle button / mouse wheel click event in firefox, I tried following which is able to catch mouse wheel click event.
$('.links').mousedown(function(e) {
if(e.which == 2) {
console.log(e.which); // prints 2
//e.preventDefault();
//e.stopPropagation();
return false;
}
});
Above code prints 2. But return false; is not working.
When I replaced console.log with alert then it works. But I can't & don't want to use alerts.
I tried mouseup, mousewheel events also. But it didn't work.
I tried attachEvent also but, I got an error(attchEvent is not a function).
I am using below mentioned js files :
jQuery-1.10.2.min.js
jquery.easyui.min.js
jquery-ui.js
jquery.ui.core.js
You can refer below links for more clarity.
jsfiddle.net/nilamnaik1989/vntLyvd2/3
jsfiddle.net/nilamnaik1989/2Lq6mLdp
http://jsfiddle.net/nilamnaik1989/powjm7qf/
http://jsfiddle.net/nilamnaik1989/q6kLvL1p/
Following are some good links. But anyhow it doesn't solve my problem.
event.preventDefault() vs. return false
event.preventDefault() vs. return false (no jQuery)
http://www.markupjavascript.com/2013/10/event-bubbling-how-to-prevent-it.html
I need your valuable inputs.
All click default actions should be cancelable. That's one of the points of this important event. However, certain browsers have exceptions:
IE 5-8 won't prevent the default on text inputs and textareas.
IE9/10 & Opera incorrectly un-check radio buttons when you click on another radio in the same group. It correctly doesn't check the new radio.
IE 5-8, Firefox, & Opera won't prevent the default on select boxes.
Firefox & Chrome feel that one radio button must be checked. If all are unchecked they’ll check the first one you click on, even if the default is being prevented.
See Events - click, mousedown, mouseup, dblclick for some more information.
I had the same issue with firefox, related with
preventDefault();
Everything was working well in Safari, Chrome, Opera and even in IE9 (not kidding)
But, after a lot of reading, I saw that the site was using and old jquery version (1.10), then updated to the latest one (2.1.4) the action was canceled even in Firefox.
Another thing to consider is that I used a variable named "keyPressed" like:
var keyPressed = event.keyCode || event.which || event.charCode
So it was easy for each browser to recognize the key event.
Hope this help!
I have faced the similar problem in FF on middle click.
The following script fixed me the issue and it works fine in FF as well.
$(document).on('click', $(".content"), function(e) {
if(e.button==1) {
e.preventDefault();
return false;
}
})

Categories

Resources