Prevent default tabbing behavior in firefox - javascript

I have few input fields to update.When press tab key I need move focus to the next field only after success of some validation of the current field. If fails then remain in the same field.
function fieldFocus(e, nxFld){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
e.stopPropagation();
e.preventDefault();
// do validate {}
if (success)
$(nxFld).focus(); //set the focus to the next fld
else
// remain in the same field
}
return false;
}
$(currFld).bind("keydown",function(e) {
return fieldFocus(e, nxtFld);
});
This works fine in IE and Chrome. But in firefox the default focus always fires before the validation. Please help me on this to prevent that default behavior of the firefox.
---- Edited Code related to #Faizul Hasan's code ----
<script>
function fieldFocus(e, obj){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
// do validate
if (0 !== obj.value.length){
var answer = confirm('Are you sure?')
if(answer)
return true;
else{
// need to stop cursor focus to the next field
e.stopPropagation();
e.preventDefault();
}
}
else{
e.stopPropagation();
e.preventDefault();
}
}
return false;
}
</script>
This is where Im getting the real problem, before user confirms the focus moves to next field in firefox. But in IE and Chrome its working fine.

Try something like this. This works fine in Chrome and Firefox too.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script>
function fieldFocus(e, obj){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
// do validate
if (0 !== obj.value.length){
return true;
}
else{
e.stopPropagation();
e.preventDefault();
}
}
return false;
}
</script>
</head>
<body>
<input type="text" id="first-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="second-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="third-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="fourth-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="fifth-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="sixth-field" onkeydown="fieldFocus(event, this);" />
</body>
Please note this is a sample code for your reference since the way you fire the function is not mentioned in your code. You can use jQuery to easily call the function for keydown event instead of calling it for all input element like onkeydown = functionName(<params>). Hope this would help you.
Updated: Same code but jQuery integrated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="jquery-1.8.2.js"></script>
<script>
$(document).ready(function(){
$('.input-element').each(function(index, value){
$(value).keydown(function(event){
fieldFocus(event, this);
});
});
function fieldFocus(e, obj){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
// do validate
if (0 !== obj.value.length){
return true;
}
else{
e.stopPropagation();
e.preventDefault();
}
}
return false;
}
});
</script>
</head>
<body>
<input type="text" id="first-field" class="input-element" />
<input type="text" id="second-field" class="input-element" />
<input type="text" id="third-field" class="input-element" />
<input type="text" id="fourth-field" class="input-element" />
<input type="text" id="fifth-field" class="input-element" />
<input type="text" id="sixth-field" class="input-element" />
</body>
</html>

After few workouts I found something with the Firefox which causes the problem. It is the 'keypress' event.
The 'keypress' event still fires when apply preventdefault() to keydown but only in Firefox.
So I handled the 'keypress' as below and solved my problem.
Hope this will help many others.
var browsFix = false;
function fieldFocus(e, nxFld){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
browsFix = true;
e.stopPropagation();
e.preventDefault();
// do validate {}
if (success)
$(nxFld).focus(); //set the focus to the next fld
else
// remain in the same field
}
return false;
}
$(currFld).bind("keydown",function(e) {
browsFix = false;
return fieldFocus(e, nxtFld);
});
$(currFld).bind("keypress",function(e) {
if (browsFix)
return false;
});

Related

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 disable TAB key in Mozilla Firefox?

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.

How to prevent invalid characters from being typed into input fields

Onkeydown, I run the following JavaScript:
function ThisOnKeyDown(el) {
if (el.title == 'textonly') {
!(/^[A-Za-zÑñ-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ-\s]/ig, '') : null;
}
if (el.title == 'numbersonly') {
!(/^[0-9]*$/i).test(el.value) ? el.value = el.value.replace(/[^0-9]/ig, '') : null;
}
if (el.title == 'textandnumbers') {
!(/^[A-Za-zÑñ0-9-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ0-9-\s]/ig, '') : null;
}
}
One of these three title attributes is given to various input fields on the page. The code works so far as invalid characters are correctly erased, but not until the next character is entered. I want to find a way to simply deny the invalid input in the first place. I appreciate your help!
Edit: I create the events globally. Here's how I do that:
function Globalization() {
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
inputs[i].onfocus = createEventHandler(
ThisOnFocus, inputs[i]);
inputs[i].onblur = createEventHandler(
ThisOnBlur, inputs[i]);
inputs[i].onkeydown = createEventHandler(
ThisOnKeyDown, inputs[i]);
inputs[i].onkeyup = createEventHandler(
ThisOnKeyUp, inputs[i]);
}
}
Globalization() is run body.onload
Therefore, a typical input field has HTML without function calls like this:
<input id="AppFirstName" style="width: 150px;" type="text" maxlength="30" title="textonly"/>
To prevent it from being set in the first place, you can return false on the keydown event handler, thus preventing the event from propagating any further.
I wrote the example below using jQuery, but you can use the same function when binding traditionally.
Though it's important to validate on the server-side as well, client-side validation is important for the sake of user friendliness.
$("input.number-only").bind({
keydown: function(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
});
The above code does it says- allows ONLY numbers. You can modify it by adding exception to say BACKSPACE for example like this
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function keyispressed(e){
var charValue= String.fromCharCode(e.keyCode);
if((isNaN(charValue)) && (e.which != 8 )){ // BSP KB code is 8
e.preventDefault();
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeydown="return keyispressed(event);"/>
</body>
</html>
$('.key-filter').keypress(function () {
if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();
});
then add the key-filter class to your input if using jquery
or
<input type="text" onkeypress="if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();" />
just put the charaters you want to allow inside the [] after the ^.
this allows all letters numbers _ - and .
You can replace your input value during the "input" event :
// <input oninput=onInput(event) />
const onInput = event => {
event.target.value = event.target.value.replace(/[^0-9+]/g, '')
}
source : https://knplabs.com/en/blog/how2-tips-how-to-restrict-allowed-characters-inside-a-text-input-in-one-line-of-code
i found this solution in: http://help.dottoro.com/ljlkwans.php
works as intended.
<script type="text/javascript">
function FilterInput (event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNumeric = (keyCode >= 48 /* KeyboardEvent.DOM_VK_0 */ && keyCode <= 57 /* KeyboardEvent.DOM_VK_9 */) ||
(keyCode >= 96 /* KeyboardEvent.DOM_VK_NUMPAD0 */ && keyCode <= 105 /* KeyboardEvent.DOM_VK_NUMPAD9 */);
modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
return !isNumeric || modifiers;
}
</script>
< body>
The following text field does not accept numeric input:
<input type="text" onkeydown="return FilterInput (event)" />< /body>
it allows text and !"#$%& but you can adjust it adding these to the validationto only allow numbers by removing the ! in the return
Code is useful for preventing user from typing any other character except number.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function keyispressed(e){
var charval= String.fromCharCode(e.keyCode);
if(isNaN(charval)){
return false;
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeydown="return keyispressed(event);"/>
</body>
</html>
You could easily do this in a single html line.
Like this to disallow spaces:
<input type="text" onkeypress="return event.charCode != 32">
Or this to only allow numbers:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
Just look up the unicode of any numbers you want to allow or disallow.
Run your code against the onkeyup event and not the onkeydown event. This way you can access the result of the very last keystroke where as the onkeyup event executes as a key is pressed without knowing its result.

Cannot disable enter key on a textarea

hi guys
i am trying to disable enter key from submitting the form in a textarea
using the following function:
function noenter() {
return !(window.event && window.event.keyCode == 13);
}
html code:
<form:form modelAttribute="myObject" method="post" action="${myUrl}">
<form:textarea path="name" class="new_obj submits_on_return" cols="40" rows="3" onkeypress="return noenter()"></form:textarea>
but it doesn't work at all, it always submits, any ideas why ?
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if(key == 13)
return false;
else
return true;
}
</script>

HDI: Disable postback on html input box

I have an input box that I don't want postback to occur on someone striking the enter key
I want the javascript event to take place instead.
<input
type="text"
id="addressInput"
onkeydown="inputenter()"
autopostback="false"/>
function inputenter() {
if (event.keyCode == 13) {
seachLocations();
return false;
}
else {
return false;
}
}
Just return false form JS function, add return false; at the end of function.
or <input type="text"
id="addressInput"
onkeydown ="return (event.keyCode!=13)"
autopostback="false"/>
UPDATE:
How about this..?
<asp:TextBox ID="TextBox1" runat="server"
onkeydown="return CallEnterKeyFunc(event.keyCode);">
</asp:TextBox>
<script type="text/javascript">
function CallEnterKeyFunc(key) {
if (key == 13) { //for FF, i think you have to use evt.which
//enter key press
seachLocations();
return false;
}
else
return true;
}
function seachLocations() {
//your code
alert("hello");
}
</script>
Special thanks to: http://www.beansoftware.com/ASP.NET-Tutorials/Accept-Enter-Key.aspx
<input type="text" id="addressInput" onkeydown="if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
searchLocations();
}" />

Categories

Resources