Create a JavaScript function that can update multiple elements when clicked without the need to target them individually

.Net 5.0 Javascript

In order to disable all elements on my UI when a specific image link, such as MouseClickIconRow1 or MouseClickIconRow2, is clicked, I encountered a challenge where I couldn't assign the same ID to all elements due to uniqueness required for UI testing purposes.

My attempt to create a loop using getElementsByName was unsuccessful, and I also tried passing in a unique element ID as shown below. As someone new to Javascript, this task has proven to be quite challenging.

HTML

<img src="@Model.MouseClickIconThumbnailUrl" id="MouseClickIconRow1" name="IconClick" onclick="DisableEnableLinks(this, true)" width="20" height="35" alt="Mouse Click Here Image"></a>

<img src="@Model.MouseClickIconThumbnailUrl" id="MouseClickIconRow2" name="IconClick" onclick="DisableEnableLinks(this, true)" width="20" height="35" alt="Mouse Click Here Image"></a>

Javascript

function DisableEnableLinks(elem ,xHow) {
    document.getElementById(elem).onclick
        = function () {
            objLinks = document.links;
            for (i = 0; i < objLinks.length; i++) {
                objLinks[i].disabled = xHow;
                //link with onclick
                if (objLinks[i].onclick && xHow) {
                    objLinks[i].onclick =
                        new Function("return false;" + objLinks[i].onclick.toString().getFuncBody());
                }
                //link without onclick
                else if (xHow) {
                    objLinks[i].onclick = function () { return false; }
                }
                //remove return false with link without onclick
                else if
                    (!xHow && objLinks[i].onclick.toString().indexOf("function(){return false;}") != -1) {
                    objLinks[i].onclick = null;
                }
                //remove return false link with onclick
                else if (!xHow && objLinks[i].onclick.toString().indexOf("return false;") != -1) {
                    strClick = objLinks[i].onclick.toString().getFuncBody().replace("return false;", "")
                    objLinks[i].onclick = new Function(strClick);
                }
            }
        }
}
String.prototype.getFuncBody = function () {
    var str = this.toString();
    str = str.replace(/[^{]+{/, "");
    str = str.substring(0, str.length - 1);
    str = str.replace(/\n/gi, "");
    if (!str.match(/\(.*\)/gi)) str += ")";
    return str;
}

Answer №1

Check out this code snippet:

const buttonContainer = document.getElementsByClassName("btnContainer");
buttonContainer[0].addEventListener("click", function() { console.log("Hello World"); });

<div class="btnContainer">
    <input type="button" id="btn1" class="jsBtn" value="button1"/>
    <input type="button" id="btn2" class="jsBtn" value="button2"/>
</div>

Answer №2

It turns out that my HTML code was wrong. I realized that specifying the unique id of each element as a string in the onclick function was necessary.

onclick="DisableEnableLinks('MouseClickIconRow1', true)"

Answer №3

If you want to retrieve elements with a specific name attribute using JavaScript, you can utilize the document.querySelectorAll() method along with a suitable selector and iterate through the results.

For instance:

document.querySelectorAll("img[name='IconClick']").forEach(function(element) {
    // Perform your actions here... for example:
    console.log(element.id);
})

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

When using Vuejs2, the list of autosize textareas connected to an expanding array of objects does not properly update their values

After binding https://github.com/jackmoore/autosize to textareas within a v-for loop, I've noticed an unexpected data persistence issue while expanding the array linked to that list: While inputs on the left side move downward as intended, new textar ...

show information retrieved from database according to the drop-down menu selection

Can anyone assist me with this query? I have a drop-down menu that includes "Shop A" and "Shop B". Shop A has a value of 1, and Shop B has a value of 2. When I select Shop A from the dropdown, I want to display the data from the database as a table specifi ...

Unsuccessful translation of HTML symbol codes within a toggle function using jQuery

Is there a way to toggle between the symbols + and - using HTML entity codes &#43; and &#45;? I have attempted different solutions for toggling HTML content, but none seem to work correctly with these specific codes. It toggles once, but doesn&apo ...

Is it possible to make a Javascript AJAX request without using server-side code?

I am currently working on a JavaScript file where I am attempting to make an AJAX call in order to retrieve JSON data. $.ajax({ type: "POST", url: "er.js", // this is the same file data: { action: 'analyzePost&ap ...

Using JavaScript to Extract Data from HTML Forms

I am currently working on parsing a form using JavaScript, instead of opting for a POST request. The form consists of one input field for the team name and multiple input fields for player names and numbers. <!-- INPUT FORM --> <div id="rosters_c ...

Can I display different text when blinking with Javascript?

I need to display text that changes every few seconds within a single div. var blink_speed = 1000; // every 1000 == 1 second, adjust to suit var t = setInterval(function () { var ele = document.getElementById('myBlinkin ...

Recurly.js: Enhancing PHP Integration with Advanced Digital Signatures

I've been working on setting up forms for a recurly implementation and using PHP to generate the signature. Despite following the documentation, searching for examples, and testing various combinations, I'm facing an issue where part of the PHP c ...

Resetting the state of toggle/click states in AJAX and jQuery

Currently, I am encountering a small dilemma with a .on function and AJAX in conjunction with a mobile menu. The mobile menu is located in the header of a site that relies heavily on AJAX for its content loading. This poses an issue because when an AJAX ca ...

Exploring Angular 1.5 components: maximizing the potential of directives with ES6!

Within the directory labeled directives, I have created two files: directives.js and color.js I have imported directives into app.js Contents of directives.js: import angular from 'angular'; import ColorDirective from './color'; co ...

Unbounded AngularJS 1.x looping of Ag-grid's server-side row model for retrieving infinite rows

I am obtaining a set of rows from the server, along with the lastRowIndex (which is currently at -1, indicating that there are more records available than what is being displayed). The column definition has been created and I can see the column headers in ...

Defining the NgRx root state key within the application state interface

Here is an example of a selector taken from the NgRx documentation: import { createSelector } from '@ngrx/store'; export interface FeatureState { counter: number; } export interface AppState { feature: FeatureState; } export const sel ...

I'm torn between choosing ToString() or GetDateTimeFormats() to properly format a DateTime. Which one would be

I have been exploring various ways to format a DateTime as a String, and I have come across limited information on this topic. After some experimentation, I have tried two methods: GetDateTimeFormats() ToString("MM/dd/yyyy") Here is the code snippet I ...

Sending JSON data results

I received this JSON response: {"data":[{"series":{"id":"15404","series_code":"TOS","publisher_id":"280","series_short_name":"Tales of Suspense","start_year":"1959","end_year":"1968","published":"1959-1968","type_id":"1","no_issues":"99","published_ ...

Is the body value null when using a web API?

I have searched for similar inquiries but have not found a solution to my specific issue. The problem I am encountering involves sending a request to my API with a content-type of application/x-www-form-urlencoded: Key Value Content-Type application/x- ...

Jumping over loop iteration following a JavaScript catch block

Currently, I am developing an API that requires making repeated calls to another API (specifically, Quickbooks Online) within a loop. These calls are encapsulated in promises that either resolve or reject based on the response from Quickbooks. Everything f ...

Error message encountered while using NEXJS Stripe v3:1 library: Unhandled promise rejection IntegrationError - Stripe() requires a valid apiKey in string format

v3:1 IntenationalIssue: Stripe() is requesting a missing value - apiKey must be a string. Encountering this issue in my Next JS project while attempting to implement a pre-built checkout with stripe. .env.local (full key has been replaced with ..... for ...

What is the process for retrieving all entries using the query state feature of Dapr?

Currently, I am utilizing the state store feature in Dapr in conjunction with the .NET client to save and retrieve items from Redis, and it is functioning properly. However, I am now faced with the challenge of retrieving all entries with a query state. I ...

Comparing textboxes on separate web pages to validate forms using AJAX on the server side

I am exploring the creation of a straightforward server-side form validation system using ajax. The objective is to verify if the data inputted by the user matches the data stored on another page. For instance, if a user enters the number 10 in a textbox ...

When running `dotnet run --project <PATH>`, the project path is not being recognized as the working directory

While utilizing the .NET commands to execute my Console App stored on a network drive, it incorrectly identifies the Working Directory as the location it is called from rather than the project path. dotnet run --project "\\network.drive\pat ...

The JSON response from Ajax is not coming back as anticipated

My attempts to make a basic ajax call are failing; var getPrevious = function(){ console.log('ajaxing'); $.ajax({ type: 'GET', dataType: "json", url: 'http://'+DOMAIN+'/previous', ...