Exploring the blur() function in JavaScript through cold calling

There is a specific line of code that I need help with.

document.getElementById("firstName").addEventListener("blur", validateField);

Additionally, there is this block of code:

validateField = (event) =>
{
    const el = event.target;
}

My goal now is to invoke the validateField() function along with the corresponding element in the

form.addEventListener('submit', function(event)
section.

document.getElementById("firstName").blur(); // I am unable to make this call.

Unfortunately, directly using blur() does not seem to be effective in this case.

The main objective is to display the bootstrap is-invalid message when the form is submitted and remains invalid.

el.classList.add('is-invalid');
el.nextElementSibling.innerHTML = "This field is required";

I am aiming to avoid utilizing jQuery as I might transition this to bootstrap version 5 in the near future.

Answer №1

It seems that when a form is submitted, the focus is removed unless the user specifically presses the enter key to submit. Perhaps an alternative method could be to set focus on another element instead of blurring the current one!

I found success with the following code:

document.getElementById("frm").addEventListener('submit', function(event) {
  event.preventDefault();
  document.getElementById("firstName").blur();
});
<form action="" id="frm">
  <input type="text" id="firstName" />
  <input type="submit" value="Press Enter" />
</form>

For an alternate solution, you can try this:

document.getElementById("frm").addEventListener('submit', function(event) {
  event.preventDefault();
  document.getElementById("frm").focus();
});
#frm:focus {
  outline: none;
  box-shadow: none;
}
<form action="" id="frm" tabindex="0">
  <input type="text" id="firstName" />
  <input type="submit" value="Press Enter" />
</form>

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

Is there ever a situation when it's acceptable to forego graceful degradation?

Currently, I am constructing a video-sharing CMS that heavily relies on jQuery and ajax for various functionalities such as rich UI effects and data submission/retrieval from the database. Unfortunately, if JavaScript is disabled, about 90% of the function ...

dirpagination fails to display all rows in the dataset

I've been working on creating tables with 3 divs, as shown in the link below:- https://github.com/anirbanmishra/congress.php/blob/master/web_test Additionally, I have a javascript file available here:- https://github.com/anirbanmishra/congress.php/bl ...

Unable to generate StumbleUpon traffic for a URL through AJAX due to the API returning text/plain

I'm attempting to acquire StumbleUpon views for a specific URL using $.ajax. This is the API I am utilizing: http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://example.com/ Here is the complete code snippet: $.ajax({ type: "GET ...

Ways to implement real-time search feature in Rails 4.2

Struggling to implement a basic search form with AJAX in my Rails 4.2 app, I've scoured numerous tutorials without success. Ruby on Rails Live Search (Filtering), https://www.youtube.com/watch?v=EqzwLUni2PM) This is the search method I'm usi ...

The combination of jQuery, using .load method in javascript to prevent scrolling up, making XMLHttpRequest requests, updating .innerHTML elements, and troubleshooting CSS/JS

While utilizing this code, CSS and Javascript are disabled (only HTML loads): function loadContent(limit) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status ...

Angular JS: Extracting the header from a CSV file

Just getting started with angular JS and I have a question. I need to take a CSV file from the user as input and then send it to the controller when they click submit. <button class="btn btn-primary" type="submit" ng-click="Input(File)">Submit</ ...

"Utilizing VueJS XHR functionality within a versatile and reusable component

Seeking advice on best practices for improving the following scenario: I have a single global reusable component called <MainMenu>. Within this component, I am making an XHR request to fetch menu items. If I place <MainMenu> in both the heade ...

Steps for converting a tsx file into a js file in React

Currently, I am in the process of a React Project and have numerous tsx files that I aim to convert for utilization as JavaScript within my project. What would be the best approach to achieve this task? ...

Accessing a peaceful API and displaying the outcome on a webpage using Node.js

I am currently working on a project that involves fetching data from a RESTful API and displaying the results on an HTML webpage using Node.js. While my code is running smoothly, I would like to ensure that the RESTful request is made every time the webp ...

Looking to retrieve the mouse coordinates using JavaScript

How can I use JavaScript to track the mouse position on a canvas? Upon visiting this page: http://billmill.org/static/canvastutorial/mouse.html They provide this code snippet: function initializeMouse() { canvasMinimumX = $("#canvas").offset().left; ...

What are the best practices for efficiently updating JSON data in a React application?

My objective is to perform CRUD operations on a JSON object stored in the state, whose structure is not fixed, but rather dynamic and subject to change. To display this JSON structure, I am utilizing a recursive functional component that keeps track of th ...

Having trouble viewing the CSS menu on Internet Explorer 8? Could it be a potential JavaScript issue causing the problem?

Receiving complaints about the menu bar dysfunction in Internet Explorer 8 has left me bewildered. Despite working perfectly on all other browsers and earlier versions of IE, I cannot figure out what's wrong with the code. You can view the website at ...

Steps for converting TypeScript code to JavaScript using jQuery, without the need for extra libraries or frameworks like NPM

My single-page dashboard is quite basic, as it just displays weather updates and subway alerts. I usually refresh it on my local machine, and the structure looked like this: project/ index.html jquery-3.3.1.min.js script.js I decided to switch it t ...

Create proper spacing for string formatting within an AngularJS modal

I am working with a popup that displays output as one string with spaces and newline characters. Each line is concatenated to the previous line, allowing for individual adjustments. Test1 : Success : 200 Test2 : Su ...

JavaScript finding items in an array

The main issue I am encountering involves receiving a notification when the term (city name within the project) entered by the user in JqueryUI Autocomplete does not match anything in the collection (e.g. user entered "My Sweet City" and it does not matc ...

Bootstrap 4 allows for the use of the d-lg-flex class to create a flexible column layout

I'm facing an issue with my table on smaller screens where some columns need to be hidden. Here's the code snippet I'm using: <table> <tr> <td>Normal 1</td> <td class="d-lg-flex d-none">hidden 1</t ...

What is it about this JavaScript code that IE8 seems to have a problem with?

Encountered an error in IE8 that has been causing trouble for me SCRIPT65535: Unexpected call to method or property access. load-scripts.php, line 4 character 25690 After removing a .js file from the code, the error disappeared. By commenting out f ...

What is the correct method for calculating the sum of one input field and multiple output fields?

I have a single input field and multiple calculated output fields using JavaScript :Click here to view the screenshot of the calculated problem You can see the live preview on this link: . When you visit this link, enter "Base on your annual bill amount: ...

Is there a way to retrieve the id of a jQuery autocomplete input while inside the onItemSelect callback function?

I am currently utilizing the jquery autocomplete plugin created by pengoworks. You can find more information about it here: Within the function that is triggered when an entry is selected, I need to determine the identifier of the input element. This is i ...

ExtJs rich text editor for text input

My attempt to insert a neatly formatted JSON string into my textarea field has been unsuccessful. I followed this method to format the string: How can I beautify JSON programmatically? and then simply used textarea.setValue(formattedJson); Take a look ...