Create a unique onblur event listener for every element in a loop in Javascript

https://i.sstatic.net/tRYul.png

I have added several items to a column in the database, but I am unsure of how to implement an onblur function for validation for each item within a loop. For example, if the NAME field is empty, I want to display an alert, and if the length of the NRIC field is less than a certain length, I also want to prompt an alert message. How can I achieve this?

  <script>
  function fnfunction(??)
  {
    //I need help with implementing validation for each item
  } 
  </script>
  <%
   String SQL   = "SELECT * FROM TB_BS_WITH UR";
   String  VALUE1 = "";
   String ROW_NO = "";
   String COL_NO = "";
    DB_Contact.makeConnection();
    DB_Contact.executeQuery(SQL);   
    while(DB_Contact.getNextQuery())
    {
        VALUE1 = DB_Contact.getColumnString("VALUE1");
        ROW_NO = DB_Contact.getColumnString("ROW_NO");
        COL_NO = DB_Contact.getColumnString("COL_NO");
    %>
   <table>
        <tr>
            <%StringTokenizer st1=n ew StringTokenizer(VALUE1, "^"); while(st1.hasMoreTokens()){%>
                <th class="fontSection">
                    <%=st1.nextToken() %>
                </th>
                <%}%>
        </tr>
        <%for(int i=0;i<Integer.parseInt(ROW_NO);i++){ %>
            <tr>
                <%for(int j=0;j<Integer.parseInt(COL_NO);j++){ %>
                    <td>
                        <input type="text"name="<%=j%>_NAME_<%=i %>" id="<%=j%>_NAME_<%=i %>" onblur="fnfunction(???)">
                    </td>
                    <%}%>
            </tr>
            <%}%>
    </table>
    <%
      } DB_Contact.takeDown();
    %>

Current outcome... How do I set up validation for each column? https://i.sstatic.net/tRos4.png

Answer №1

One way to validate on the blur event is by implementing the following approach.
Avoid assigning the event directly within the input tag; instead, assign it after the page has finished loading.

  window.addEventListener('load', initializePage, false);

  // attach blur event to all input fields
  function initializePage(event) {
    var inputs = document.getElementsByTagName('INPUT');
    for (var i = 0; i < inputs.length; i++) {
      // only consider text fields
      if (e.target.type === 'text') {
        inputs[i].addEventListener('blur', performValidation, false);
      }
    }
  }

  // validate the value of the blurred element
  function performValidation(e) {
    e = e || window.event;
    e.target = e.target || e.srcElement;

    // assuming the id format always follows --> #_FieldName_#
    var fieldName = e.target.id.split('_')[1];

    switch (fieldName) {
      case 'Name':
        if (e.target.value === '') {
          alert(fieldName + ' cannot be left empty!');
          e.target.focus();
        }
        break;

      case 'NRIC':
        if (Number(e.target.value) < 10) {
          alert(fieldName + ' must be at least 10 characters long!');
          e.target.focus();
        }
        break;
    }
  }

Answer №2

To achieve this, you can follow the example below:

Using JSP:

<input type="text"name="<%=j%>_NAME_<%=i %>" id="<%=j%>_NAME_<%=i %>" onblur="validateInput("+<%=j%>+",this)">

Please pay attention to:

onblur="validateInput("+<%=j%>+",this)"
, where this refers to the current input element.

In JavaScript:

 function validateInput(cellNo,currentInput){

    if(cellNo === 0){
       // Retrieve the value from currentInput and validate it according to your requirements.
    }else if(cellNo == 1){
     // Retrieve the value from currentInput and validate it according to your requirements.
    }
     .
     .
     .
}

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

Tips on sending asynchronous requests to a PHP page using jQuery AJAX

As a newcomer to web development, I am working on creating a social networking website for a college project. One feature I want to implement is updating the message count in the menu every time there is a new message in the database for the user (similar ...

Exploring ways to showcase informational alerts when a link is hovered over by the mouse

I am currently working on a website that showcases links utilized by my team. One specific requirement is that when a user hovers over a link, note information should be displayed. Although the simplest solution would be to not list the link if it's n ...

Preventing Cross-Site Scripting (XSS) when injecting data into a div

I am using Ajax to fetch data in JSON format and then parsing it into a template. Here is an example of the function: function noteTemplate(obj) { var date = obj.created_at.split(/[- :]/), dateTime = date[2] + '.' + date[1] + '. ...

The Angular UI Datepicker is not reflecting changes in scope variables within the dates-disabled function

I'm currently working with AngularJS and the Angular UI Bootstrap. I've encountered an issue that I initially thought was related to scope, then initialization, but now I'm stuck trying to figure out what's causing the problem. I' ...

Send data in JSON format along with an identifier using Jquery AJAX

I am having trouble sending JSON data along with 2 IDs using a jQuery AJAX post. Despite my efforts, I can't seem to get it working. Here is the code snippet in question: try { var surveyID = localStorage.getItem("surveyId"); var userDetails ...

Is MapView in React Native restricted to explicit markers only?

I'm facing a challenging problem while working on my app's mapview. I have been struggling to find a solution for dynamically repopulating the mapview. Initially, I attempted the following approach: render() { const dynamicMarker = (lat, long, ...

The operation to remove the child element could not be completed

var first_content = document.getElementById('first-content'), offered_games = document.getElementById('offered-games'); for(var i = 0, e = offered_games.children; i < e.length; i++) { e[i].onmouseenter = function() { var ...

What are the steps to fixing the date time issue between NextJS and Firebase?

I am facing an issue with Firebase Database returning timestamps and unable to render them into components using Redux. How can I resolve this error and convert the timestamp to a date or vice versa? I need help with valid type conversion methods. import ...

Utilize JSON data loading instead of directly embedding it onto the page for improved website

I've integrated Mention.js into my website, allowing a dropdown list of usernames to appear when "@" is typed in a designated textarea. <textarea id="full"></textarea> While it's functioning well, the examples provided only show how ...

Modal obstructing BsDatePicker

<!-- The Server Modal --> <div class="modal" id="serverModal"> <div class="modal-dialog" style="max-width: 80%;overflow-y: initial !important;" > <div class=" ...

When altering the color of a mesh in Three.js, only a single face is impacted by the modification

I have a GLB model with multiple parts and hierarchy. My goal is to highlight a specific part of the assembly on mouseover. The code snippet I am using for this functionality is as follows: raycaster.setFromCamera( pointer, camera ); ...

JavaScript is not designed to run a second time

Currently, I have a script set up using $(document).ready(). It works perfectly upon initial loading. However, I also need this script to execute whenever the user changes an HTML select control. Ideally, upon page load, I want the filter and sort functio ...

Retrieve JSON object by matching another JSON property

I am working with an array of id's and their respective contents in a JSON response. My goal is to retrieve the content based on the received id. For instance, if the ID is 1 (returned from the JSON), I aim to access the JSON data using "data.id" (wh ...

Tips for adding values to an object

Behold, a complex object in multiple dimensions: let b = {} b.push({hello:'xyz'}) This method is currently inactive ...

Variability in Swagger parameter declaration

Is it possible to specify input parameters in Swagger with multiple types? For example: Consider an API that addresses resources using the URL http://localhost/tasks/{taskId}. However, each task contains both an integer ID and a string UUID. I would like ...

Refresh your webpage automatically without the need to manually refresh after clicking a button using AJAX in HTML and PHP!

One issue I'm facing is that the page doesn't auto-refresh, although it loads when I manually refresh it. Below you can find my HTML and AJAX code along with its database details. The Trigger Button <?php $data = mysqli_ ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

Having trouble loading my app.js in Angular - Seeking help on Coursera!

I've followed the instructions provided thus far and inserted the HTML code accordingly. However, upon attempting to load the page, all I see is: The tabs: The Menu Appetizers Mains Desserts The description: image: dish.name , dish.name , dish.labe ...

Generating a React User-Object in JSON Format

Imagine there is a back-end system using Node.js that allows the creation of users with specific attributes as shown below: POST http://localhost:8080/user Authorization: {{adminToken}} Content-Type: application/json { "userID": "test" ...

Unable to remove the most recently added Object at the beginning

I am currently working on a project to create a dynamic to-do list. Each task is represented as an object that generates the necessary HTML code and adds itself to a div container. The variable listItemCode holds all the required HTML code for each list it ...