Can you stop a JavaScript event using another event?

Can you prevent a JavaScript event in the queue from being executed by another event?

Situation:

I have two ASP.Net controls,
Age - TextBox
Save - Button

There are two JavaScript validation functions,
ValidateAge() - verifies if the age is between 0 and 140, shows an alert if invalid
ValidatePage() - checks that all required fields are filled in before saving

<asp:TextBox ID="txtAge" TabIndex="1" DataType = "String" runat="server" MaxLength="50" CssClass="textBox" Style="width: 150px" CausesValidation="true" onblur="return ValidateAge();"></asp:TextBox>

and a specific access key for the button,

<asp:Button ID="btnSave"  AccessKey="S" AssociatedControlID="btnSave" TabIndex="1" runat="server" CssClass="ButtonSaveNew" onclick="return ValidatePage();"></asp:Button>

When I press Alt+S with an invalid age in the Age field, first the onblur of the Age field is triggered (as I've set the AssociatedControlID), followed by the onclick of the Save button.

However, regardless of the age's validity, the save action is executed.

I want to be able to stop the execution of the onclick event of the button if the age is invalid in the onblur event of the textbox.

Answer №1

It seems that the issue is related to your form automatically submitting, causing the button not to trigger the onclick event as intended. This behavior may also occur when pressing enter within a form field, resulting in a form submission.

To address this, you can register the ValidatePage function as a handler for the submit event on the form:

<form onsubmit="ValidatePage()">

If you are working with WebForms, incorporating client-side validation may require using the jQuery.validation plugin. This can provide a more streamlined approach to validation, especially if you are already utilizing jQuery. While integration with WebForms may require some adjustments, resources like Dave Ward's post can offer guidance on making it work effectively:

Answer №2

Is it possible to prevent a java script event from triggering another event?

In general, it is not possible to cancel one event with another. The blur event cannot be canceled. It is also complicated to maintain focus as discussed in how to prevent blur() running when clicking a link in jQuery?.

In my opinion, holding onto focus when a user tries to move to the next element (and focus on the next input) may not be very user-friendly. Instead, it would be better to display a validation error message for the input that the user is leaving. The only event that should be prevented is submit when validation fails, and in that case, you can focus on the first invalid field.

var ageValid;
$("#txtAge").change(function validateAge(e) {
    if(!isNaN(this.value) && this.value >= 0) {
        ageValid = true;
    } else {
        $(this).addClass("invalid");
        ageValid = false;
    }
}).change();
$("#formid").submit(function validatePage(e) {
    // maybe calls to the single validation functions?
    if (! ageValid) {
        e.preventDefault();
        $("#txtAge").focus();
        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

Resizing an image with six corners using the canvas technique

Currently, I am facing two issues: The topcenter, bottomcenter, left and right anchors are not clickable. I'm struggling with the logic to adjust the image size proportionally as described below: The corner anchors should resize both height and wi ...

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

Using jQuery AJAX to send data containing symbols

When making an AJAX call, I am including multiple values in the data like this: var postData = "aid="+aid+"&lid="+lid+"&token="+token+"&count="+count+"&license="+license; postData = postData + "&category="+category+"&event_name="+e ...

Is npm create-react-app giving you trouble?

When attempting to create a React app using the command npm create-react-app appname, the tool would just return me to the same line to input more code. I also gave npx a try, but encountered some errors in the process. See this screenshot for reference: ...

Using NodeJS and EJS to Display MySQL Query Results

I am currently working on a project where I need to display data retrieved from a MySQL query in an HTML table. However, when I attempt to do so, I encounter the following output: [object Object],[object Object],[object Object],[object Object],[object Obj ...

Having trouble targeting a div with jQuery

Is it possible to target a specific div within an unordered list and list items? I'm having trouble with it. Here is the HTML code: <ul class="grid"> <div id='categoria' cat='web'></div> <li id=' ...

Understanding how to bind data in JavaScript client-side templates

I've started incorporating Client Side templates into my JavaScript code. Currently, I'm using the $create method to bind a Sys.UI.DataView to my data. The "data" variable contains a JSON result with 100 records, all of which are being bound by ...

Problems encountered with nested AJAX calls and the $.when.apply function handling deferred promises efficiently

I am attempting to create a triple nested series of AJAX calls, as shown in the basic structure below (fail calls have been omitted). Progress is being made up to the second level with the eventCalls. The final when.apply.done only triggers after every si ...

Validation of user input alongside input masking using jQuery

One issue that I am encountering is that form inputs with assigned masks (as placeholders) are not being validated as empty by jQuery validation. I am using: https://github.com/RobinHerbots/jquery.inputmask https://github.com/1000hz/bootstrap-validator ...

Setting a specific time zone as the default in Flatpickr, rather than relying on the system's time zone, can be

Flatpickr relies on the Date object internally, which defaults to using the local time of the computer. I am currently using Flatpickr version 4.6.6 Is there a method to specify a specific time zone for flatpickr? ...

Vue component not displaying object property

I am currently working on implementing a filter method in a Vue component. Here is the filter method I am trying to use: filterHotels:function(){ var thisHotels = this.hotelRoomArr; console.log(this.hotelRoomArr['107572']['rooms ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

arrange a collection within an array containing keys as strings

I am facing an issue with sorting an array of objects. I need to sort the 'list' by 'score' in descending order. var list =[{ '440684023463804938': { score: 6, bonuscount: 2 }, '533932209300832266': { score: 20, b ...

Issue: The data type 'void' cannot be assigned to the data type 'ReactNode'

I am encountering an issue while calling the function, this is just for practice so I have kept everything inside App.tsx. The structure of my class is as follows: enum Actor { None = '', } const initializeCard = () => { //some logic here ...

Learn how to dynamically modify the text and color of a column value within a <v-data-table> component in Vue.js 2.6.11 and Vuetify 2.2.11 based on a specific condition

In my current project where I am developing a web application using ASP.NET CORE for the backend and vue.js for the frontend, I encountered an issue with Vuetify's CRUD Datatable UI Component in a page named "Category". The problem arises when trying ...

Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using: expect(classList).toContain('Rail__focused') However, I encountered the following error: Error: expect(received).toContain(expected // inde ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

Three.js WebGL shader compilation error

I am currently new to webgl and learning shaders. My current project involves wrapping a texture around a sphere to create an earth globe image. However, I have encountered issues with the fragments and vertex GLSL code. The error I am facing occurs when ...

Can a library be developed that works with both Java and JavaScript/TypeScript?

I specialize in Angular development. Our front- and backend both contain specialized calculation methods that work like magic. Although the classes are the same, any bugs found in the calculations have to be fixed separately in two different projects. Is ...

Arrange the Proxy Array of Objects, the localeCompare function is not available

Encountering an error while attempting to implement ES6 arrayObj.sort(a,b) => a.property.localeCompare(b.property) syntax: Getting TypeError: a.property.localeCompare is not a function. Suspecting that localeCompare might not be in scope, but unsure ...