What could be causing this function to work in Google Chrome, but not in Firefox?

For some reason, in Firefox, this section of the code never returns true. However, it works perfectly fine in Google Chrome.

if(restrictCharacters(this, event, digitsOnly)==true)

The expected behavior is that if a user inputs a number from 1 to 5 in the input box with the ID E1Rating, the function should return true and execute the nested code below. But in Firefox, nothing happens after a participant enters a number.

I have isolated the problematic part of the code to show you how it's being utilized.

document.getElementById("E1TimeStart").value = startTime;       
$('#E1Rating').keyup(function() {
    if(restrictCharacters(this, event, digitsOnly)==true){                  
        clearTimeout(mytimeout);                                                                        
        var rateTime = new Date().getTime();                
        $('#E1Rate').hide();                                                
        document.getElementById("E1TimeEnd").value = rateTime;              
        PrepareBox2();                                                      
    }
    else{
        //Do nothing and wait for the timeout
    }
});

};

Here is the restrictCharacters function. It has been tested and confirmed to work in Chrome. Interestingly, it also works in Firefox when used outside of the if == true block. I suspect that the issue might be related to the event reference in (this, event, digitsOnly). But I'm not entirely sure what specifically could be causing it.

/* Purpose: Code will restrict false until it detects the numbers 1 through 5 */
/* Code Source: originally from qodo.co.uk */
// create as many regular expressions here as you need:
var digitsOnly = /[1-5]/g;

function restrictCharacters(myfield, e, restrictionType) {
    if (!e) var e = window.event
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    var character = String.fromCharCode(code);

    // if they pressed esc... remove focus from field...
    if (code==27) { this.blur(); return false; }

    // ignore if they are press other keys
    // strange because code: 39 is the down key AND ' key...
    // and DEL also equals .
    if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
        if (character.match(restrictionType)) {
            return true;
        } else {
            return false;
        }

    }
}

Answer №1

You must specify event as a parameter in the function. Both Google Chrome and IE support the non-standard global event property, which points to the most recent event object.

$('#E1Rating').keyup(function(event) { //<--
    if(restrictCharacters(this, event, digitsOnly)){

Tip: You can safely substitute if (.. == true) with if (...), as any expression that is equal to true will evaluate as true."

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shifting attention from one input to another by utilizing a barcode scanner

Utilizing a barcode scanner, I am inputting data into the fields of a webpage. The form is set up with autofocus on the initial input field. However, upon entering the first barcode in the opening field, the focus should shift to the following input field. ...

Encountering the error message "Uncaught Promise (SyntaxError): Unexpected end of JSON input"

Below is the code snippet I am using: const userIds: string[] = [ // Squall '226618912320520192', // Tofu '249855890381996032', // Alex '343201768668266496', // Jeremy '75468123623614066 ...

Tips for altering Koa's HTTP status code for undeclared paths

If an undefined route is accessed on a Koa server, what is the best method to change the default HTTP status code and response body? Currently, Koa returns a 404 status and 'Not Found' text in the body. I intend to modify this to 501 (Not implem ...

Is it possible to include a base url for imports in React JS?

Conventional method for adding imports: import Sample from ‘../../../components/signup’ I want to simplify imports by removing the front dots and slashes: import Component from ‘components/signup’ Is there a way to set a base URL for imports to ...

Interact with multiple databases using the singleton design pattern in a Node.js environment

I need to establish a connection with different databases, specifically MongoDB, based on the configuration set in Redis. This involves reading the Redis database first and then connecting to MongoDB while ensuring that the connection is singleton. Here i ...

Activate a click on a div element to enable smooth scrolling when using the page down and page up keys

Whenever I directly click on my div, the pageUp and pageDown keys scroll the contents of the div. But when I trigger a click programmatically, the scrolling with pageUp and pageDown stops working. How can I enable scrolling with pageUp and pageDown without ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Hide the menu when tapping outside on a tablet device

Currently working with HTML, CSS, and JS (specifically Angular) I have a Header menu that contains dropdown sub-menus and sub-sub-menus in desktop view. On a PC, the sub-menus appear on hover and clicking on an entry redirects you somewhere. Clicking o ...

Learn how to increase spacing in React applications

I'm currently utilizing the Grid component from @material-ui to present my data. Within this Grid, I have several nested grids, each representing a different section. I've implemented the container spacing attribute of the Grid and set it to the ...

"Discovering a button press using the Gamepad API: A Step-by-Step Guide

I'm currently building a web page that can detect button presses on an Xbox controller and display a boolean value based on the pressed button. Right now, I have successfully managed to detect when a controller is connected and show it as a string. Ho ...

What steps can be taken to repair the script?

https://jsfiddle.net/fnethLxm/10/ $(document).ready(function() { parallaxAuto() }); function parallaxAuto() { var viewer = document.querySelector('.viewer.active'), frame_count = 5, offset_value = 500; // init control ...

Ensuring the input field and button are positioned in a horizontal line

Currently, I am developing a to-do list application using React and Chakra UI. I am trying to align the input field and the button on the same line for a more organized layout. This is the current layout: image I aim to achieve a design similar to this: ...

How do I search for a JSON object in JavaScript?

I have an array containing screen resolutions and I need to find the correct resolution range for the user's viewport (I have the width x height of the current window). Here is the sample JavaScript array with JSON objects: [ {width:100,height:200, ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

What's the best way to retrieve the dates for the current week using JavaScript?

Could anyone help me find a way to retrieve the first and last dates of the current week? For example, for this week, it would be from September 4th to September 10th. I encountered an issue at the end of the month when dates overlap two months (such as t ...

Mongoose - run a function on a designated date within the document

Currently, I am developing a cryptocurrency-based betting game project. My database of choice is mongodb and I utilize mongoose for interaction with it. Within this database, I have a collection that houses documents detailing various betting games. Each d ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...

"When setting up a window.EventListener, the Div element fails to be hidden when setting its display property to 'none

I'm working on creating a preloader by displaying an overlay until all the content on the page is loaded. However, despite checking my code multiple times, I can't seem to figure out why it's not working. If anyone could provide some assist ...

What is preventing me from retrieving the parameter in the controller?

I could use some assistance with implementing pagination for displaying data. However, I am encountering issues in retrieving the parameter in the Controller Method. To provide more context, I have created a demo on CodePen which can be viewed at http://c ...

Ways to prevent images from vanishing when the mouse is swiftly glided over them

Within the code snippet, the icons are represented as images that tend to disappear when the mouse is swiftly moved over them. This issue arises due to the inclusion of a transition property that reduces the brightness of the image on hover. However, when ...