Unable to prevent key blocking with event listener

<body id="body" runat="server" onkeydown="return showKeyCode(event)">

Whenever a key is pressed, IE8 (or in compatibility mode) triggers an exception pointing to an issue in line x, which is related to the body tag. How can I resolve this? The JavaScript code seems to be working fine with IE compatibility mode (but not with Chrome). Additionally, the code is not functioning properly in IE and Firefox (it does not block F5 and Enter key).

--> Object expected

var version = navigator.appVersion;

function showKeyCode(e) {
    var keycode = (window.event) ? event.keyCode : e.keyCode;

    if ((version.indexOf('MSIE') != -1)) {
        if (keycode == 13) {
            event.keyCode = 0;
            event.returnValue = false;
            return false;
        }
    }
    else {
        if (keycode == 13) {
            return false;
        }
    }
}

Another issue I am encountering involves a simple JavaScript code in IE and Firefox (works in Chrome):

Nothing happens & --> Object expected

 <a onclick="ClearTextboxes();" title="Close" id="close" runat="server">Close</a>

....inside script tags:
 function ClearTextboxes() {
     document.getElementById('<%= txtbox_name.ClientID %>').value = '';
     document.getElementById('<%= txtbox_email.ClientID %>').value = '';
     document.getElementById('<%= txtbox_content.ClientID %>').value = '';
     document.getElementById('<%= ResultMail.ClientID %>').style.display = 'none';

 }

Answer №1

Your showKeyCode function has a lot of unnecessary code. The following simplified version will work just as well. You are already guaranteed that e will reference the key event object due to the way you are passing in event in the body's onkeydown attribute. Browser sniffing is not needed. Using return false is the correct method to prevent the browser's default action when using a DOM0 key handler, so e.returnValue is unnecessary.

Blocking F5 can cause issues, and unless there is a very good reason, it's best not to do it since users expect it to refresh the page. By adjusting the function as shown below, it should successfully prevent the default action of the Enter key:

function showKeyCode(e) {
    if (e.keyCode == 13) {
        return false;
    }
}

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

What causes the issue of divs not stacking properly when using Bootstrap 4?

I'm currently working on integrating VueJs and bootstrap4 to create two basic components. However, I am facing an issue where I have assigned the class .col-md-4 to a div in order to add 3 elements per row, but only one element is being added per row ...

Is it possible to access a class with protected/private fields written in TypeScript from outside the class in JavaScript?

Currently, I am delving into TypeScript classes (though my experience with OOP is limited). The following code snippet is extracted from the chapter on classes in https://www.typescriptlang.org/docs/handbook/classes.html Here's the issue at hand: I ...

transfer information using dropzone

I am currently working with Dropzone and have implemented the following code: <form action="#" class="dropzone" ></form> Within the JavaScript code, the dropzone function is set to upload images only when a button with the id "startUpload" i ...

Transforming the playbackRate property of a web audio-enabled audio element

I recently experimented with integrating an audio element into the web audio API using createMediaElementSource and achieved success. However, I encountered an issue when attempting to change the playback rate of the audio tag. Despite trying multiple appr ...

Showing JSON response on an HTML page using AngularJS

I have limited experience with JavaScript and/or Angular, but I am required to utilize it for a research project. My task involves showcasing the JSON data returned by another component on a webpage. Here is how the process unfolds: When a user clicks on ...

looping through the multi-dimensional array using v-for

Interested in using v-for and I have encountered a scenario with an object structure as seen here: https://i.sstatic.net/wNguk.png Upon inspecting the dev console, the object looks similar to this: https://i.sstatic.net/jyqth.png My query is about how to ...

BS Modal was improperly invoked, leading to an illegal instantiation

Currently, I am attempting to trigger a bootstrap Modal in Angular by utilizing the component instead of its HTML attribute. However, I am encountering an error (specifically, illegal invocation). Here is the code snippet from the component: @ViewChild(&a ...

Unable to locate the 'react-native' command, attempted various fixes but none were successful

Working on an older react native project that was functioning perfectly until I tried to pick it back up and encountered a problem. https://i.stack.imgur.com/1JUdh.png This issue revolves around the package.json file. https://i.stack.imgur.com/v6ZEf.png ...

Error message stating that there is an issue with the `this.extButton` variable being null when attempting to manually adjust the toolbar settings for

When using aloha in a web application, I have found it to be very effective and capable of performing all necessary tasks. However, I have run into an issue when attempting to customize the toolbar with the following settings: Aloha.settings = { ... ...

Utilize Javascript to access Django Rest Framework API and obtain a Token

I've successfully set up an API with Django Rest Framework that functions well when accessed through cURL, HTTPie, or the browsable API. The API utilizes token authentication, requiring initial credentials to obtain a token. To achieve this using HTTP ...

Java's equivalent to the return function in JavaScript

Currently, I am in the process of adapting three.js into Java while also incorporating my own modifications and enhancements. One specific challenge I am facing involves determining the best approach for managing reflection within the code. As part of thi ...

Hide bootstrap card on smaller screens such as sm and md

Utilizing the Bootstrap 4.1 card component, I showcase categories within the right sidebar - check out a sample image of the card here: Card example image; When viewing on smaller screens, it's preferable to collapse this large card as shown in this ...

What is the significance of XmlHttpRequest's readyState being at 2 when receiving a 200 HTTP response

Currently, I am utilizing pure JavaScript (no jQuery) to send a file to the server. The PHP script on the server returns status code 200 upon completion, but the JavaScript is interpreting it as readyState == 2. The PHP code responds with status code 200: ...

I am unable to get the Javascript code `window.print()` to function

I tried creating a basic link to print a page on my website using Google Chrome, but for some reason, the link is not working. Upon checking my console log, I noticed an error message that says: Maximum call stack size exceeded Here is the HTML code I us ...

Using HTML and jQuery to create a table with buttons to add or remove rows is a common practice. However, there

I have created a simple table with an "Add Row" button. Each new row has a "Remove" button. However, I am facing an issue in binding the 'click' event for the class 'remove'. Here is the code snippet: <script src="https://ajax.googl ...

Struggling with updating scope values when binding data in Angular (particularly with a slider)

Currently, I am utilizing Angular to develop a tool that can take user input from a slider tool and dynamically update an "estimate" field whenever the values are adjusted. However, I'm encountering an issue where the data is only binding in one direc ...

Travis is checking to see if the undefined value is being

My experience with jasmine testing has been successful when done locally. However, I am encountering issues on Travis CI where all the API tests are returning undefined values. Here is an example: 4) Checking Server Status for GET /api/v1/orders - Expecte ...

What is the best way to show nested objects in JavaScript?

let paragraph = document.createElement('p'); document.body.appendChild(paragraph) const fruit = { type: 'Apple', properties: { color: 'Green', price: { bulk: '$3/kg', smallQty: '$4/kg' ...

Adding items to a JSON document

My task involves creating a pseudo cart page where clicking on checkout triggers a request to a JSON file named "ordersTest.json" with the structure: { "orders": [] }. The goal is to add the data from the post request into the orders array within the JSO ...

What are the best practices for sharing context in express and typescript?

Implementing a solution to expose a value to all request handlers using express and typescript is my goal. I am looking for a way to easily "inject" this value from a middleware or an alternative method that allows for simple mocking if needed. Here is th ...