What is the process for attaching a JavaScript function to a specific element on the page?

In my webpage, I have multiple elements with unique IDs that all contain textboxes and labels as attributes.

  • Element 0

    • Textbox
    • Textbox
    • Label
  • Element 1

    • Textbox
    • Textbox
    • Label
  • Element 2

    • Textbox
    • Textbox
    • Label

I want to show an error message when a user types in any of the textboxes. To do this, I've added an onkeydown JavaScript function to each attribute like so:

MyTextbox.Attributes.Add("onkeydown", "javascript:OnChangeData();");

This is my JavaScript function:

<script type="text/javascript">
    function OnChangeData() {
        var info = document.getElementById('<%= infoControl.ClientID%>');
        infoDonneePersonnelle.textContent = "Error!";
    }
</script>

Although everything seems to be working fine, there's an issue: When I type in a textbox of element 1 (which has ID 1), the error message appears in the last element with ID 5 instead of the first one where I typed.

In summary, I have 6 elements displayed with attributes. Whenever I type in a textbox of element 1, the error message is displayed in the last element regardless of where I actually made the input. How can I ensure that the error message is shown in the correct element based on its ID?

Answer №1

Revise your usage of OnChangeData to include the element reference when calling the function. By using OnChangeData(this), you will pass the reference of the specific element that triggered the event.

<script type="text/javascript">
    function OnChangeData(element) {
        var parentElement = element.parentElement;
        var personalDataInfo = parentElement.querySelector('.error-message');

        if (personalDataInfo) {
            personalDataInfo.textContent = "Error!";
        }
    }
</script>

Answer №2

If I were to manage this situation, I would opt for delegated event handling coupled with relative DOM navigation:

  1. Firstly, it's essential to ensure that the overarching container housing these repetitive setups is uniquely identifiable on the client side during runtime - be it through an ID or a distinct class.

  2. Within the said overarching container, make sure that the containers encompassing these repeated setups share a common class.

  3. Utilize JavaScript to attach event listeners such as keydown (or perhaps more suitably input) to the overarching container.

  4. Upon the occurrence of the event, determine which specific container from step #2 it transpired in by utilizing the closest method on the event's target.

  5. Locate the error display element through querySelector within the wrapper.

Here’s a practical example. For demonstrative purposes, I’ve set it up so that adding a digit to the fields results in an error message being displayed and removed:

document.getElementById("container").addEventListener("input", (event) => {
    // Locate the wrapper containing this input
    const wrapper = event.target.closest(".wrapper");
    // If no wrapper is found, or the target isn't an input, exit
    if (!wrapper || event.target.tagName !== "INPUT") {
        return;
    }
    
    // Obtain the input value
    const value = event.target.value;
    
    // Find the error element
    const errorElement = wrapper.querySelector(".error");
    
    // Display or clear the error message
    if (/\d/.test(value)) { // Placeholder for the error condition
        errorElement.textContent = "No digits allowed";
    } else {
        errorElement.textContent = "";
    }
});
.error {
    min-height: 1.2rem;
    color: #A00;
}
<!-- The parent container; alternatively, use document.body if necessary -->
<div id="container">

    <div class="wrapper">
        Element 0
        <div><input type="text"></div>
        <div><input type="text"></div>
        <div class="error"></div>
    </div>

    <div class="wrapper">
        Element 1
        <div><input type="text"></div>
        <div><input type="text"></div>
        <div class="error"></div>
    </div>

    <div class="wrapper">
        Element 2
        <div><input type="text"></div>
        <div><input type="text"></div>
        <div class="error"></div>
    </div>

</div>

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

Query in SQL to retrieve numbers that are multiples of a specified value

To create a candlestick graph, I need to convert the following table: amount created_at updated_at 258 2019-10-17 01:45:17 2019-10-17 01:45:17 186 2019-10-17 01:45:17 2019-10-17 01:45:17 122 2019-10-17 01:46:31 2019-1 ...

The MVC framework coupled with a robust Javascript/JQuery validation library is a winning

Currently, I am involved in a project that utilizes MVC 2.0 along with Kendo UI. Our team has made the decision to utilize AJAX validation instead of MVC Model level validation. This means that validation occurs during most "onchange" events on HTML contro ...

Include quotation marks around a string in C# to convert it into JSON format

I am utilizing a service that operates with JSON format. However, the JSON data I am receiving does not include double quotes around keys and values. Here is an example of the data I have: [{name:{buyerfirstname:Randy, buyermiddlename:null, buyerlastnam ...

Steps to send an object array using a promise

I've put in a lot of effort but haven't found a solution that works well for me. I attempted using promise.all and setting the array globally, but it didn't work out. My goal is to search through three MongoDB collections, match the finds, ...

Assistance with Troubleshooting a Complicated JavaScript/TypeScript Software

As someone new to the world of Javascript and Typescript, I am looking to gain a deeper understanding of how a specific large application runs through its steps. Can anyone suggest a debugger or other helpful tool for this task? ...

Restrict magnification in THREE.js mousewheel interaction

Seeking advice on limiting zoom in and out of a model in three.js. I have explored trackball controls, but couldn't find a way to restrict zooming. I also experimented with orbit controls, but encountered issues when combined with trackball controls r ...

Newbie in JavaScript - reinitiating my for loop journey

After running an animation in 4 steps, I want it to restart once all the steps are completed. var aSteps = [ { "x": "800", "y": "0" }, { "x": "800", "y": "500" }, { "x": "0", "y": "500" ...

Show the word "Delivered" on the submission button once the message has been sent successfully

Is it possible to customize the "Submit" button text on Contact Form 7 in WordPress? I would like it to change to "Sent" once the user has submitted the form, providing them with feedback that the message has been successfully sent. Thank you for your he ...

ASP C# Sorted and Paged

I have encountered an issue while trying to implement search, paging, and sorting in my ASP.NET MVC5 application. The error message I keep receiving is: "The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'O ...

What is the best way to tidy up a function within a useEffect hook?

When updating state within a useEffect hook while using async/await syntax, I encountered an error regarding the cleanup function. I'm unsure how to properly utilize the cleanup function in this scenario. Error: Warning - A React state update was att ...

Ways to display the chosen value based on the item's index using Javascript in Angular

If you want to view the complete code, just click on this link. I have identified the main issue here. Check out the code here: https://stackblitz.com/edit/test-trainin-2?file=src/app/app.component.html The problem is when you interact with the green bal ...

"Allow clients to upload and preview images on the front end without any need for server

I am looking to enhance my website by allowing users to upload an image and preview it without having to post back. I need to incorporate a file upload control (such as HTMLinputfile or ASPfileupload) where the user can browse to select an image, followed ...

When the React ref current is accessed from outside the component where it is initialized, it returns

Encountering an issue with React ref. Today, I was pondering on how to access DOM elements from sub-components within a main component. Fortunately, I stumbled upon a solution using React refs on a website. I set up a ref in my main component and linked i ...

Determine the output based on the data received from the ajax post request

I am seeking a way to validate my form based on the data returned. Currently, the validation only returns false if the entire post function is false. Is there a solution to differentiate how it is returned depending on which condition is met? This is my ...

A guide on utilizing jQuery to decode JSON data

Recently, I've started learning about JSON and jQuery. I have a JSON file stored at a URL with the following format: { "united":[ {"Atlanta","California","Alabama"} ] "canada":[ {"Ontario","British Columbia"}, ] } My ...

Creating a model for this JSON data in C# is a straightforward process that involves defining

How can I structure a model for the provided JSON data? {"code":"1", "message":"OK","response": {"user":{"id":"124","usertype":"29","currenttime":"2013-04-24T08:09:20.487+00:00","sessionid":"2bcf1c92-9b97-47d8-8995-b39cf7cbe2af"}}} This is my impleme ...

Ways to dynamically assign a class to a single element within a group of identical elements

I have three identical items in the DOM. Specifically, I am referring to a moving line <span class="caret"></span> <ul> <li class="nav-item-1"> <a href="#">ITEM 1</a> <span class="caret"></span> ...

Update the package.json file to match the contents found in the node_modules directory

Received a project that was previously in progress by someone else. I noticed that when copying it, the node_modules folder must also be copied for it to function properly. Is there a way to automatically update the package.json file according to the con ...

GeckoDriver in Firefox causes an error when trying to .Quit() in Selenium version 3.0.1

Current Environment: Firefox 50.0.2 64bit, C#, Visual Studio 2015, Windows Server 2012 R2, Azure, ClearScript.V8.5.4.7, Selenium.Mozilla.Firefox.Webdriver.0.6.0.1, Selenium.WebDriver.GeckoDriver.Win64.0.11.1 I have implemented a solution using ClearScript ...

Handling empty values in JSON data when sending it to the controller through AJAX

Attempting to transmit the following JSON data from View to Controller: { "allselected": false, "selectedIds": ["", "all"], "targetControl": "Studieniva", "targetSource": "studienivalist", "dependency": [{ "name": "ShopNo", ...