Run a Javascript function when the expected event fails to happen

I currently have this setup:

<input type="text" name="field1" onblur="numericField(this);" />

However, I am struggling to figure out how to execute the numericField() function for the element before the form is submitted. I attempted using

document.getElementById("Campo1").onblur()
, but it only returns undefined. Does anyone know how I can accomplish this task?

Answer №1

It's important to avoid binding events in the way you're currently doing it. Instead, consider using element.addEventListener.

If your goal is to validate a form before submission, here's the correct approach:

document.querySelector("form").addEventListener("submit",function(){

  // Validate your fields - use numericField() on both input fields
  // If numericField returns true or false, the submit action will be cancelled if validation fails
  return numericField(your_element);
});

To trigger a blur event on a specific element, you can use this code:

var el = document.querySelector("<select your element here>");
el.focus();
el.blur();

In HTML5, you can also perform direct validation of input fields on blur by correctly defining the type (e.g. number for Number inputs) and/or using the pattern attribute. This allows browsers to trigger intrinsic validation upon blur.

Answer №2

If you want to take action before submitting, consider creating a validation function for better clarity. For instance: using JQuery.

<form id="form">
...
</form>

Here is an example of jQuery code that can be used to perform actions before the form is submitted:

$(function() {
    $('#form').submit(function() {
        // DO STUFF
        return true; // return false to cancel form action
    });
});

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

Exploring Angular2's ability to interpret directive templates using the ng-container

Recently delving into angular2, I ventured into creating dynamic forms and generating fields by following the guide provided in this URL. The result was as expected. The dynamic form component renders each field one by one using ng-container, like shown b ...

Tips for initializing a jstree with no content?

When I click a button, I send a key to the controller and retrieve my lists using JSON. The array inside my lists serves as my children in my jstree. $("#btnSearch").on("click", function () { alert("I'm also here"); $.ajax({ ...

Encountering a ReferenceError message that says "readFile is not defined

Currently, I am in the process of learning Node.js and encountering an issue. When I type 'node .' in the terminal, I receive a ReferenceError: readFile is not defined message. Below is the code snippet: const express = require("express"); co ...

Having trouble changing the chosen selection in the material UI dropdown menu

I've encountered an issue with my material ui code for a select dropdown. It seems that the selected option is not updating properly within the dropdown. <FormControl variant="outlined" className={classes.formControl}> <InputLabel ref={ ...

Generate three random names from an array and assign them to an element

This website is amazing! I've interacted with so many awesome people here! Currently, I have successfully implemented code to get one random name from an array. However, I now want to display three different names each time, and I'm facing a roa ...

Identifying JSON Attributes in Nonexistent Objects Function

Is there a method to verify the existence of a property in JSON data without specifying a particular object? Here's an example: data.programs.text.background In this case, background is a property of text. But what if the text object doesn't e ...

Guide on how to forward the response obtained from an Ajax call to a different HTML page

I am working with a mongoose database that stores data containing an individual's first and last name. The user inputs their first name into a field, triggering an ajax request sent to the file named controller.js. This file generates a JSON response ...

trigger the f:setPropertyActionListener function upon clicking the button following the onclick event

On a page with a datatable displaying all users, each row includes "edit" and "delete" buttons. The issue arises when trying to delete a user by clicking on the "delete" button. Upon clicking the button, a confirmation dialog is displayed using PrimeFaces ...

Is it possible to determine whether a path leads to a directory or a file?

Is it possible to distinguish between a file and a directory in a given path? I need to log the directory and file separately, and then convert them into a JSON object. const testFolder = './data/'; fs.readdir(testFolder, (err, files) => { ...

Update a particular package using Node

Is there a way to update Browser-sync without updating all my node packages? I need the version with the Browser-sync GUI, but I don't want to update everything else. ├─┬ <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Tips for implementing Animation.css in Angular version 1.5.8

I have successfully added the ngAnimate dependency to my AngularJS project: var app=angular.module('testApp',['ngRoute', 'ngAnimate']); I have also included the animation classes in my animation.css file: .slide-animation.n ...

The background image is not appearing on the div as expected

I've been attempting to create a div and set a background image for it using jQuery, but I seem to be facing issues. When I try setting the background color to white, it works fine. Here's the code snippet: function appendToDom(poster) { ...

Enhance a path SVG component with properties for a map in a React application

My goal is to develop a strategy game using an SVG map that I have created. I want to include attributes such as "troops" in each "path" representing territories, along with other properties. Can I add these attributes to individual paths and then use this ...

Optimizing Performance by Managing Data Loading in JavaScript Frameworks

I am new to JavaScript frameworks like React and Vue, and I have a question about their performance. Do websites built with React or Vue load all data at once? For example, if I have a page with many pictures, are they loaded when the component is used or ...

Move a div by dragging and dropping it into another div

Situation Within my project, there is a feature that involves adding a note to a section and then being able to move it to other sections, essentially tracking tasks. I have successfully implemented the functionality to dynamically add and drag notes with ...

Problem with autocomplete functionality in Angular Material's md-contact-chips

Having some trouble with the autocompletion feature of md-contact-chips. I want to capture the $query as soon as someone starts typing. HTML <md-contact-chips ng-model="members" md-contacts="querySearch($query)" md-contact-name="fullname" ...

Creating a heading transition that moves from the bottom to the top with CSS

I am looking to add an animation effect to the H1 element in my program. I want it to smoothly appear from the bottom hidden position using a CSS transition when the page loads. How can I achieve this? Additionally, I need the height of the bounding elemen ...

Explore by the anchor tag

I've recently implemented a search bar utilizing Bootstrap. This is the code for the search bar: <div class="md-form mt-0"> <input class="form-control" id="myInput" type="text" placeholder="Sear ...

Unable to display child component using VueRouter

Recently, I started delving into VueJS and decided to create a new Vue application using vue-cli. After making a few modifications, this is what my router.js looks like: import Vue from 'vue' import Router from 'vue-router' import Hell ...

Getting the click event object data from a dynamically created button with jQuery or JavaScript

I have a task of tracking page button click events. Typically, I track the objects from statically created DOM elements using: $('input[type=button]').each(function () { $(this).bind('click', function () { ...