How can I modify my for loop with if else statements so that it doesn't just return the result of the last iteration in

Today is my first day learning JavaScript, and I have been researching closures online. However, I am struggling to understand how to use closures in the code I have written:

function writeit()
{
    var tbox = document.getElementById('a_tbox').value;
    var letters = tbox.split("");
    for(var i=0;i<letters.length;i++)
    {
        if(letters[i]==="a")
        {
            document.a_form.b_tbox.value = i+1 + ". character is a";
        }
        else if(letters[i]==="b")
        {
            document.a_form.b_tbox.value = i+1 + ". character is b";
        }
        else
        {
            document.a_form.b_tbox.value = i+1 + ". character is not a nor b";
        }
    }
}

I am trying to extract a string from a text box, convert it into an array, and modify each value using a for loop. Ideally, if a user inputs "abc" into the text box, I would like the output to be "1. value is a 2. value is b 3. value is not a nor b". However, the current output only shows "3. value is not a nor b". How can I correct this issue?

Answer №1

Instead of replacing the value of the textbox with each iteration of your loop, use += to add on for each iteration. Here's how you can do it:

document.a_form.b_tbox.value += i+1 + ". character is not a nor b";

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

What strategies can be implemented to maximize the efficiency of this asynchronous block of code?

var orderItems = userData.shoppingcart; var totalPrice = 0; userData.shoppingcart.forEach(function(itemName, i){ _data.read('menuitems', itemName, function(err, itemData){ if(!err && itemData) { totalPrice += i ...

Experiencing Difficulty Retaining Checkbox State Using LocalStorage Upon Page Reload

At the moment, I have a script that automatically clicks on a random checkbox whenever the page loads or refreshes. Through localStorage, I can also view the value of the input assigned to the randomly selected checkbox. However, I'm facing an issue ...

Universal - Permissible data types for function and constructor arguments

In many statically typed languages, it is common to specify a single type for a function or constructor parameter. For example: function greet(name: string) { ... } greet("Alice") // works greet(42) // error TypeScript is an extension of JavaScri ...

I am having trouble grasping certain syntax in JavaScript when it comes to using `${method_name}`

I'm having trouble understanding some of the syntax in this code, particularly ${method_name}. I'm not sure what we are achieving by passing the method name within curly braces. global._jsname.prototype.createEELayer = function (ftRule) { if ...

React Native SectionList Divided by Dates

I have a task to reformat my date object where I have an array of dates in the following format: Object { "FREETIME": "2021-04-19 11:30:00", }, Object { "FREETIME": "2021-04-19 12:00:00", }, Object ...

How can I modify my code to ensure that trs and th elements are not selected if their display property is set to none?

I am currently working on creating a filter for my pivot table, but I am unsure of how to dynamically calculate the sum of each row/column based on whether they are displayed or not. If you need any other part of my code, feel free to ask. To hide employee ...

How do I ensure a single row in my table constantly remains at the bottom?

I am currently working on developing a MUI table that shows rows, with the last row displaying the total number of colors. The challenge I am facing is ensuring that the last row always stays at the bottom when there are no results in the table. I have att ...

Comma styling in JavaScript

What is the reasoning behind developers choosing to format commas in code this particular way? var npm = module.exports = new EventEmitter , config = require("./lib/config") , set = require("./lib/utils/set"); As opposed to this formatting style? va ...

Show only the lower left quadrant within the img tag during the prepend operation

I'm attempting to add an <img> tag in front of a <div> similar to this example on JSFiddle. However, I have a specific requirement to only display the bottom left quarter of the image instead of the entire one. HTML Markup <div id="my ...

Change the size of the individual cells within JointJS

I have some code for a jointjs demo that includes basic shapes on a paper. I am looking to adjust the size of the shapes or highlight them when clicked on or when the cursor moves over them. var graph = new joint.dia.Graph; v ...

Guide to importing an AngularJS controller into an Express file (routes.js)

Currently, I am in the process of developing a restful service and my goal is to organize my callbacks within controllers in order to avoid cluttering my routes.js file. Previously, I had been using controller = require(path.to.controller); This enabled ...

What is the best way to transform a JSON object from a remote source into an Array using JavaScript?

Attempting to transform the JSON object retrieved from my Icecast server into an array for easy access to current listener statistics to display in HTML. Below is the JavaScript code being used: const endpoint = 'http://stream.8k.nz:8000/status-json ...

extracting numerical values from a string using javascript

Currently, I am engaged in a project that requires extracting phone numbers from a string. The string is stored in a JavaScript array called dine. { "group": 1, "tel1": "Tél(1): 05.82.77.31.78", "tel2": "Tél(2): 09.55.86.31.45", }, ,... My goal i ...

A guide on executing a double click action on an element in Selenium Webdriver with JavaScript specifically for Safari users

Having trouble double clicking an element in Safari using Java / Webdriver 2.48. All tests work fine on IE, Chrome, and Firefox but Safari does not support Actions. Currently attempting: executor.executeScript("arguments[0].dblclick();", element); or ...

Controller encountering JSON null data

I am currently working on a feature that allows users to send multiple email/SMS messages by selecting checkboxes. However, I am facing an issue where the data is not being passed correctly from my JavaScript function to the action method - all the data sh ...

What is the process for getting the input value when a key is released?

My goal is to capture the actual value or text from an input field and store it in a variable. However, when I use the console to check the output, it shows me a number indicator that increments each time I type something. <input id="usp-custom-3" ty ...

Updating Text within a Label with jQuery

Seeking assistance with a jQuery issue that I am struggling to resolve due to my limited experience. Despite attempting to search for solutions online, I have been unable to find an alternative function or determine if I am implementing the current one inc ...

Highlight all the written content within the text box

I'm struggling with a piece of code that is supposed to select all the text inside an input field: <input id="userName" class="form-control" type="text" name="enteredUserName" data-ng-show="vm.userNameDisplayed()" data-ng-model="vm.enteredUs ...

What is the best way to implement JQuery in order to trigger an event in a text box whenever the user hits the "enter

Also, refrain from submitting the form if the user hits enter in THAT PARTICULAR input field. ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...