The onclick value within a loop is only effective for the final value in the table

As someone who is new to Javascript, I am embarking on the journey of creating a unit conversion calculator. My goal is to loop through a table and assign an onclick event that will display the value of the clicked button.

So far, I've managed to obtain a NodeList which I am iterating through. However, when I add the onclick event, each button click only outputs the value of the last button in the list.

var x = document.getElementsByName("Scalar")

var out = document.getElementById("output")

function Edit(Input){
    out.innerHTML = Input;
}

var i;
for (i = 0; i < x.length; i++) {
    out.innerHTML = out.innerHTML + x[i].name;
    var b = x[i];
    b.onclick = function() {
        Edit(out.innerHTML + b.value)
    }
    
}
<input type = "button" id="Scalar" value = "K" name = "Scalar"/>

<div id="output">

</div>

When I click any button, my output ends up being the value of the last button in the list (DDDDDD).

Answer №1

It's important to note that variable b is being overwritten within the same code block. To ensure accuracy, utilize this.value instead of b.value. Avoid defining a function inside a loop as it may lead to variable overwriting issues. Consider using addeventlistener in place of onclick for better functionality. var x = document.getElementsByName("Scalar")

var out = document.getElementById("output")

function Adjust(){
    out.innerHTML = this.value
 }

for (i = 0; i < x.length; i++) {

   x[i].addEventListener( 'click' , Adjust );

 }

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

How can you ensure a div stays at the top or bottom of a page based on the user's scrolling behavior?

Hello there! While I know there have been many questions regarding sticking a div to the top or bottom while scrolling, my particular issue is a bit more specific. My dilemma is that I am looking for the div to stick either to the top or the bottom based ...

Customizing translations for various domains in Vue-i18n

Our app has a global reach and our company is undergoing a rebranding process in certain markets. For instance, we are currently known as "Acme Company" in the U.S. and Canada, but now we aim to be recognized as "Acme Company" in the U.S. and "Foo Company ...

Obtaining the website link using Django's template language

Is there a way in the Django template language to reference the URL? I want to use it on static pages to avoid live links. Can this be accomplished without JavaScript? I am hoping to achieve something similar to: {% if current_url == "/about/" %} About { ...

What is the best method for defining validation rules in Vuelidate to ensure a value matches the value of a specific field within an

Imagine having a Vue component with data structured like this: data: () => ({ form: { old_password: { data: '', type: 'password', label: 'Old Password', }, new_password: { ...

Using switch statement upon page loading in AngularJS

I am currently working on refactoring a switch statement that identifies specific classes upon page load into one of my controllers. Does anyone have suggestions on how I can transform this straightforward task using Angular? $('.radior').eac ...

Sending asynchronous requests to handle data within various functions based on different links

I'm currently facing a major roadblock when it comes to resolving my issues with callbacks. I've gone through resources like How to return value from an asynchronous callback function? and How to return the response from an Ajax call?, among seve ...

Can the name of the ngx-datatable-column be altered?

I recently started developing an angular2 web application that includes a ngx-datatable component. The header columns all have numeric names, but I would like to customize them in the view. Despite my efforts to research this issue, I haven't come ac ...

Implementing Custom Directive and Events in an Ongoing Application Process

As I design a custom directive for a third-party jQuery plugin, I encounter issues with updating data using events. My directive is set to listen for these events and use $apply to ensure proper data updates from the controller. Additionally, I aim to enab ...

What is the best way to extract the date January 1, 1970 from a datepicker?

Currently, I am utilizing a datepicker along with a function that converts dates from dd-mm-yyyy to yyyy-mm-dd format. The dates in the database are stored in yyyy-mm-dd format, so I need to first convert them to dd-mm-yyyy for better readability. When sub ...

Vitest does not currently support the experimental syntax 'jsx' in use

Currently utilizing Vite with the vitest package Error: Details: ...

Using a PHP array as a parameter in a link for an AJAX function

I am attempting to pass a PHP array to an AJAX function in order to populate dynamically created tables. To achieve this, I need to pass the values in an array all at once to avoid the issue where only the last dynamic table is populated. However, it see ...

Click the JavaScript button to activate the delete function

Imagine an interactive HTML table where a user can easily delete rows by either selecting a row and pressing the delete key on their keyboard or by clicking a designated delete button. This functionality ensures a smooth and intuitive user experience. Se ...

Utilizing traditional JavaScript variables within Express.js or Node.js: A comprehensive guide

How can I successfully export variables from regular JavaScript to be used in ExpressJS? I attempted to use 'exports' but it didn't yield the desired results. For instance, in a regular JS file: var search = 'hello'; exports = s ...

Angular HttpClient does not support cross-domain POST requests, unlike jQuery which does

I am transitioning to Angular 13 and I want to switch from using jQuery.ajax to HttpClient. The jquery code below is currently functional: function asyncAjax(url: any){ return new Promise(function(resolve, reject) { $.ajax({ type: ...

Mobile devices experiencing issues with mouse events

My 360 panorama image works perfectly on desktop, but I'm having trouble getting the mouse events to work on mobile phones. How can I resolve this issue? // listeners document.addEventListener("mousedown", onDocumentMouseDown, false); document.addEv ...

Submitting the information through a for loop for every array within the nested array using Ajax

My data consists of a Sensor and multiple Alarms related to this Sensor. I am attempting to create several Alarms using a for loop, and then I want to use these Alarm variables in the Sensor JSON object. However, I am facing difficulties with this process. ...

Mobile site's call button functionality is malfunctioning

For the telephone number on my mobile site, I employed the <a href="tel:+1800229933">Call us free!</a> code. However, it seems to be malfunctioning on several devices. Any insight on this issue would be greatly appreciated. Thank you. ...

Is it possible to achieve the full image when utilizing double buffering for drawing on canvas?

I have a code where I am using two canvas elements to draw an image in order to prevent flickering. However, I am facing an issue where I cannot get the full image to display when using this method. When I use just one canvas, the image displays fine. It ...

When using a file uploader to set an image on v-model in Vue JS, it sometimes results in

I am currently using Vue JS 2 to develop an image uploader functionality. The input in question has a change function that triggers a function and sets the selected file to the v-model property. After logging the data, I noticed that only an empty object ...

Tips for accessing the post body within an express route

Currently, I am in the process of learning how to construct a web application through the utilization of express, node, and angular. As part of this journey, I have encountered a situation where I am capable of transmitting a post request from angular to t ...