How to disable TAB key in Mozilla Firefox? - javascript

I want to disable the tab key in my HTML form. I found following JavaScript code to disable tab, but it doesn't work in Firefox (working in Chrome and IE).
<script type="text/javascript">
document.onkeydown = function () {
if (window.event && window.event.keyCode == 9) { // Capture and remap TAB
window.event.keyCode = 9;
}
if (window.event && window.event.keyCode == 9) { // New action for TAB
alert('The TAB key was pressed');
return false;
}
}
</script>
This is my HTML form:
<body>
<form>
<input type='text'><br>
<input type='text'><br>
<input type='text'><br>
<input type='text'><br>
<input type='text'><br>
<input type='text'><br>
<input type='text'><br>
<input type='submit'><input type='reset'>
</form>
</body>

event.stopPropogation() or event.cancelBubble() (for certain version of IE) will stop an event from propagating upwards, including the default handler.
As others have said, it's a bad idea to be preventing tab from working properly. From a user's point of view, disabling tab is likely to become very irritating.

I've dabbled in allowing the tab key to be used in textareas, perhaps you can derive further from this.
<form>
<textarea rows="15" cols="82"></textarea>
</form>
<script>
function initTabinput() {
window.addEventListener('keydown', tabListener.bind(area), false);
}
var area = document.getElementsByTagName('textarea')[0];
var tabListener = function (evt) {
if ('keyCode' in evt && evt.keyCode === 9) {
evt.preventDefault();
var caretPos = this.selectionStart;
var beforeCursor = this.value.substring(0, caretPos);
var afterCursor = this.value.substring(caretPos);
caretPos += 1;
this.value = beforeCursor + "\t" + afterCursor;
this.setSelectionRange(caretPos, caretPos);
}
};
window.addEventListener('load', initTabinput, false);
</script>
NB. This is absolutely not cross-browser compatible code and has been tested only in recent versions of Chrome.

Related

Automatic keypress on page load

I have an input area where a value has been preset. I would like to make it so that on page-load the "enter" button is pressed on the keyboard to submit the value.
Here is the code:
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
}
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
A solution where I would not need to press enter and the value is submitted is also welcome!
I guess code below would work.
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
console.log('triggered')
player_name = $(this).val();
logged = 1;
}
})
const event = new Event('keypress')
event.which = 13
document.querySelector('#login-input').dispatchEvent(event)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
The doc
If you want it to run after page loaded, use onload event. The solution may look like this:
<script>
function f() {
// Test it:
// alert("Hello, page loaded!");
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="f()">
If you do want user to have a glimpse on your pre-filled login form and inform about what is happening, you may make a delay with setTimeout function, which will fire in 0.5 sec after onload event happened.
<script>
function f() {
$('#some_element').text('Signing you in...');
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="setTimeout(f, 500)">
Or you can call the event handler with a faked keypress like this:
function kpress(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
console.log(player_name,logged);
}
}
kpress.call($('#login-input').keypress(kpress),{which:13});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
I use the output from the jQuery event binding as the object context for the Function.prototype.call() method and add a "simplified" event object as {which:13}.

How to use javascript to validate the input field for restricting numbers only and setting the range as maximum and minimum

On event change the overflow value must get rejected.
I have an input box in my form, where I want to restrict the user to enter only the numbers between 0 and 99999 only. But I don't want to disable the tab button functionality. The below code is working fine for "NUMBERS only" but it won't allow to use Tab button as well. Also it's not checking the overflow condition if someone enters number bigger than 99999.
<script>
function myIdFunction() {
var txt = "";
if (document.getElementById("EmpId").validity.rangeOverflow) {
txt = "Value too large";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
<input type="text" name="id" id="EmpId" ng-model="EmpId" max="99999"
onchange="myIdFunction()" onkeypress="return IsNumeric(event);"
ondrop="return false;" onpaste="return false;" ng-disabled="!edit"
placeholder="EmpId" required>
<span id="error" style="color: Red; display: none">* Input digits (0 -)</span>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) ||
specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>
<input type=number min=0 max=99999>
Brought to you by:
For the specification see:
WHATWG HTML, section 4.10.5.1.13
For supported browsers see:
Can I use: Number input type
The Current State of HTML5 Forms: The min, max, and step Attributes
For older browsers use:
number-polyfill
(A polyfill for implementing the HTML5 <input type=number> element in browsers that do not currently support it.)
Live enforcement of correct values
If you don't want the user to be able to enter incorrect values while typing:
var last = '';
input.addEventListener('input', function () {
if (this.checkValidity()) {
last = this.value;
} else {
this.value = last;
}
});
See: DEMO.

ascii enter key return 0 through javascript in firefox

I am trying to submit a form through Javascript with a simple code. When user press Enter key form should submit.
My code works on chrome, safari and ie , but it does not work on FireFox . It's better to say charCode attribute from event object return 0 instead 13.
JS Works on Chrome and the others :
var up = document.getElementById('up');
var handler = function(e){
if(e.charCode == 13){
document.getElementById("sendForm").submit();
}
}
up.keypress = addEventListener('keypress',handler);
JS Works on FireFox
var up = document.getElementById('up');
var handler = function(e){
if(e.charCode == 0){
document.getElementById("sendForm").submit();
}
}
up.keypress = addEventListener('keypress',handler);
HTML
<form method="POST" id='sendForm' action='http://google.com'>
<textarea rows="4" cols="50" id='up'></textarea>
<input type='submit' name='sub'>
</form
Don't use keypress and e.charCode use keydown and e.keyCode. That will get you "13" across all browsers for "Enter".

java script not working until refresh the page

My requirement is my text box should not accept the script tags(i.e < and >). When I open the page first time my text box does not allow script tags(i.e < and >).
After some time it allows only alphanumeric characters. When I refresh the page it works fine. Can any one help this. how can i get solution for this? or is there any easy way for this.
my code:
<input name="headerTextBoxs" id="headerTextBox" size="55" type="text" onKeypress="return keyRestricted(event)", onKeydown="return keyRestricted(event)" value="" />
<script type="text/javascript">
function keyRestricted(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var keychar = String.fromCharCode(key);
//alert(keychar);
var keycheck = /[a-zA-Z0-9]/;
if ( (key == 60 || key == 62)) // not allowing script tags
{
if (!keycheck.test(keychar)) {
theEvent.returnValue =false ; //for IE
if (theEvent.preventDefault) theEvent.preventDefault(); //Firefox
}
}
}
</script>
Another way:
My requirement is same that is not allow script tags(i.e < and >). Here the problem is it works fine in mozilla firefox. but in google cromo and IE browsers my textbox not allowing backwards text (i.e left arrow(<-)). simply i wrote like this.
My code:
<input name="headerTextBoxs" id="headerTextBox" size="55" type="text" onkeyup = "this.value=this.value.replace(/[<>]/g,'');" />
This works OK for me.
<!DOCTYPE html>
<html>
<head>
<script>
function keyRestricted(e) {
e= e|| window.event;
var key= e.keyCode || e.which;
var keychar= String.fromCharCode(key);
var keycheck = /[a-zA-Z0-9]/;
if ((key == 60 || key == 62)){
if (!keycheck.test(keychar)) {
e.returnValue =false ;
if (e.preventDefault) e.preventDefault();
}
}
}
</script>
</head>
<body>
<input size="55" type="text" onKeypress="keyRestricted(event);" value="" />
</body>
<html>
I would use the change event to do this.
<input type="text" name="name" onchange="validate(this);"/>
function validate(input_element) {
if( /(<|>)/.test( input_element.value ) ) {
alert( "< and > are not allowed characters" );
}
}
This has less of an impact on performance and you can also use the validate function later on if necessary.
Demo here
Try onkeyup event only if you want to be it more or less responsive.
onchage event will occur when you will focus out the <input>, so it will be kinda post factum.

how to detect copy and paste in javascript?

I have two fields, one is emailid and another is password in my form. I want to prevent the user from pasting into those fields. They should be forced to enter manually, like Google Forms.
2020 update
There are copy and paste events you can use to prevent these actions, or to modify the data being copied or pasted. (see the links for browser support)
<input type="text" onpaste="return false">
Or the longer javascript version:
const elem = document.getElementById('nopaste');
elem.addEventListener('paste', (event) => {
event.preventDefault();
});
<input type="text" placeholder="can paste"><br>
<input type="text" id="nopaste" placeholder="can not paste">
You could disable ctrl+v combination and right click as well.
for IE, you may tap into following event handlers:
onpaste="return false;"
oncut="return false;"
oncontextmenu="return false;"
oncopy="return false;".
Here is a workaround for all browsers:
function noCTRL(e) {
var code = (document.all) ? event.keyCode : e.which;
var ctrl = (document.all) ? event.ctrlKey : e.modifiers & Event.CONTROL_MASK;
var msg = "Sorry, this functionality is disabled.";
if (document.all) {
if (ctrl && code == 86) {
//CTRL+V
alert(msg);
window.event.returnValue = false;
} else if (ctrl && code == 67) {
//CTRL+C (Copy)
alert(msg);
window.event.returnValue = false;
}
} else {
if (ctrl == 2) {
//CTRL key
alert(msg);
return false;
}
}
}
In HTML section, your fields would look like:
Email :<input name="email" type="text" value=""/><br/>
Password :<input name="password" type="password" value=""/><br/>
Confirm Email :<input name="email" type="text" value="" onkeydown="return noCTRL(event)"/>
Confirm Password :<input name="password" type="password" value="" onkeydown="return noCTRL(event)"/>
I don't think user can copy password fields if input type is password
Hope this helps.
Note:
Disabling JavaScript in browser will let users do whatever they want
Always Keep this in mind: respect user's freedom.
You should use onpaste. The paste event fires when the user attempts to paste text.
HTML
<h3>Play with this text area:</h3>
<textarea id="editor" rows="3">Try copying and pasting text into this field!</textarea>
<h3>Log:</h3>
<p id="log"></p>
JavaScript
function logCopy(event) {
log.innerText = 'Copied!\n' + log.innerText;
}
function logPaste(event) {
log.innerText = 'Pasted!\n' + log.innerText;
}
const editor = document.getElementById('editor');
const log = document.getElementById('log');
editor.oncopy = logCopy;
editor.onpaste = logPaste;
2022 UPDATE:
For Input Elements to receive onChange event on paste action, mention onpaste option as below
<input onpaste='return true' onChange={handleChange}/>
Copy
document.addEventListener("copy", (e) => {
console.log("copy")
});
Paste
document.addEventListener("paste", (e) => {
console.log("paste")
});

Categories

Resources