What is the best way to extract the innerHTML of every button and exhibit it in a text box?

How can I create a simpler JavaScript code for clicking buttons to input letters into a text box? Instead of creating getElementByID for each button, is it possible to use some kind of loop?

<div id="alpha" >
    <br/>
    <div align="center">
        <button id="q" class="letters">Q</button>
    </div>
    <div align="center">
        <button id="w" class="letters" onclick="theclick()">W</button>
    </div>
    <div align="center">
        <button id="e" class="letters">E</button>
    </div>
     <div align="center">
        <button id="r" class="letters">R</button>
    </div>
     <div align="center">
        <button id="t" class="letters">T</button>
    </div>

    **INITIAL JAVASCRIPT WITH ONLY THE ONCLICK FUNCTION FOR BUTTON "W"**

What's the best way to simplify this JavaScript code without having an onClick function for every single button?

<script>

    function theclick() {

        var x = document.getElementByClassName("letters").innerHTML;
        document.getElementById("textbox").value = x;
    };

</script>

Answer ā„–1

If you're looking for a simple solution using vanilla JavaScript, here is one approach to consider:

// Define a named function as the event handler:
function buttonOutput() {

  // Cache the textarea by its id attribute:
  let textarea = document.querySelector('#result');

  // Update the textContent of the textarea with the textContent of the clicked element (trimming white-space):
  textarea.textContent += this.textContent.trim();
}


// Retrieve all <button> elements with the 'letters' class from the document:
let buttons = document.querySelectorAll('button.letters'),

  // Convert the NodeList into an Array:
  buttonArray = Array.from(buttons);

// Iterate over the array of <button> elements:
buttonArray.forEach(

  // Assign the buttonOutput() function as the event handler for the 'click' event:
  button => button.addEventListener('click', buttonOutput)
);
div > div {
  text-align: center;
}
div > button {
  width: 30%;
  text-align: center;
}
<div id="alpha">
  <div>
    <button id="q" class="letters">Q</button>
  </div>
  <div>
    <button id="w" class="letters" onclick="theclick()">W</button>
  </div>
  <div>
    <button id="e" class="letters">E</button>
  </div>
  <div>
    <button id="r" class="letters">R</button>
  </div>
  <div>
    <button id="t" class="letters">T</button>
  </div>
  <div>
    <button id="y" class="letters">Y</button>
  </div>
</div>

<textarea id="result"></textarea>

Check out the JS Fiddle demo.

This code snippet uses ES6 features like `let`, `Array.from()`, and Arrow functions. If you need compatibility with older browsers, here's an ES5 alternative:

// Define a named function as the event handler:
function buttonOutput() {

  // Use 'var' instead of 'let':
  var textarea = document.querySelector('#result');

  textarea.textContent += this.textContent.trim();
}


// Retrieve all <button> elements with the 'letters' class from the document:
var buttons = document.querySelectorAll('button.letters'),

  // Convert the NodeList into an Array:
  buttonArray = Array.prototype.slice.call(buttons);

// Iterate over the array of <button> elements:
buttonArray.forEach(function(button) {
  // Assign the buttonOutput() function as the event handler for the 'click' event:
  button.addEventListener('click', buttonOutput);
});
div > div {
  text-align: center;
}
div > button {
  width: 30%;
  text-align: center;
}
<div id="alpha">
  <div>
    <button id="q" class="letters">Q</button>
  </div>
  <div>
    <button id="w" class="letters" onclick="theclick()">W</button>
  </div>
  <div>
    <button id="e" class="letters">E</button>
  </div>
  <div>
    <button id="r" class="letters">R</button>
  </div>
  <div>
    <button id="t" class="letters">T</button>
  </div>
  <div>
    <button id="y" class="letters">Y</button>
  </div>
</div>

<textarea id="result"></textarea>

Try the ES5 version on JS Fiddle.

For more information, check out these references:

Answer ā„–2

One way to achieve this functionality using jQuery is as follows:

$(function() {
  $('.letters').on('click', function() {
    $('#textbox').text( $('#textbox').text()+$(this).text() );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textbox"></div>
<div id="alpha" >
  <div align="center">
    <button id="q" class="letters">Q</button>
  </div>
  <div align="center">
    <button id="w" class="letters">W</button>
  </div>
  <div align="center">
    <button id="e" class="letters">E</button>
  </div>
  <div align="center">
    <button id="r" class="letters">R</button>
  </div>
  <div align="center">
    <button id="t" class="letters">T</button>
  </div>
</div>

Vanilla JavaScript Approach

var letters = document.getElementsByClassName("letters");

var addLetter = function() {
  var val = document.getElementById("textbox").innerHTML,
      thisVal = this.innerHTML;
  document.getElementById("textbox").innerHTML = val + thisVal;
};

for (var i = 0; i < letters.length; i++) {
  letters[i].addEventListener('click', addLetter, false);
}
<div id="textbox"></div>
<div id="alpha" >
  <div align="center">
    <button id="q" class="letters">Q</button>
  </div>
  <div align="center">
    <button id="w" class="letters">W</button>
  </div>
  <div align="center">
    <button id="e" class="letters">E</button>
  </div>
  <div align="center">
    <button id="r" class="letters">R</button>
  </div>
  <div align="center">
    <button id="t" class="letters">T</button>
  </div>
</div>

Answer ā„–3

Here is a simple Vanilla JS solution for the problem:

var buttons = document.querySelectorAll("#alpha button");

for(var i =0; i < buttons.length; i++){
  var btn = buttons[i];
  btn.addEventListener("click", function() {
    document.getElementById("textbox").value += this.innerHTML;
  });
}
<div id="alpha">
  <div align="center">
    <button id="q" class="letters">Q</button>
  </div>
  <div align="center">
    <button id="w" class="letters">W</button>
  </div>
  <div align="center">
    <button id="e" class="letters">E</button>
  </div>
  <div align="center">
    <button id="r" class="letters">R</button>
  </div>
  <div align="center">
    <button id="t" class="letters">T</button>
  </div>
</div>
<input id="textbox">

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

Floating elements can be vertically aligned with spans

I am facing an issue with aligning three spans vertically inside a div. It seems simple to achieve, but vertical alignment is not working properly when I use float. My goal is to have the light blue bar vertically centered. Here is the code snippet: .co ...

Building a navigation system with previous and next buttons by implementing JavaScript

I am currently working with AngularJS and I have data that is being received in the form of an array containing two objects. As a newcomer, I am still trying to figure this out. data[ { "something":"something1", "something":"something1", "something":"some ...

Can integer values be stored in localStorage similar to JavaScript objects and retrieved without requiring typecasting?

After setting an integer value to a localStorage item: localStorage.setItem('a', 1) and checking its data type: typeof(localStorage.a) "string" it shows as a string. I then typecast it to an int for my purposes: parseInt(localStorage.a) My ...

Is there a way to gather selected checkboxes from all child checkbox components in vue?

I have a unique setup where my table rows are generated by child components, each containing a checkbox. I am looking for a way to retrieve all the checked checkboxes at once without using two-way binding or updating an array on the parent component. Here ...

Is it possible to use tabs.create to generate a tab and then inject a content script, where the code attribute is effective but the file attribute seems to be ineffective

I am currently facing an issue with injecting a content script file into a newly created tab. The problem lies in the fact that I keep receiving an error stating chrome.tabs.executeScript(...) is undefined in the console output of the Popup. It may be wort ...

The function history.popstate seems to be malfunctioning, as it is triggered by both the forward and backward navigation buttons in

When I press the back button, I am attempting to retrieve the previous state. Upon inspecting, I noticed that the popstate function is also triggered by the forward button. However, it does not revert to the previous state even though the popstate function ...

Tips for creating CSS styles for a selected input field

I seem to be stuck in a situation where my screen looks similar to the screenshot provided. There are four input elements that I would like to have bordered just like in the image, complete with a circled tick mark. I've managed to create these four i ...

Requesting an API token through the body using Javascript's Fetch function

I'm currently working on developing a frontend application using Javascript Fetch to interact with an API service. One of the tasks I need to accomplish is to create a token by using the POST method and sending an apiKey parameter in the Body. Once I ...

When a parent document is deleted, Mongoose automatically removes any references to child documents

Greetings everyone, thank you for taking the time to read my query. I am looking to remove a child object that is referenced in a parent object. Below is the structure: const parentSchema: = new Schema({ name: String, child: { type: mongoose.Schema. ...

What is the best way to incorporate a loading icon onto a webpage that exclusively runs JavaScript functions?

I frequently use Ajax load icons to indicate progress during ajax requests. Is there a way to achieve the same result using regular JavaScript? For instance: $('button').on('click', function(){ showLoadingIcon(); lengthyProces ...

After changing the value of a <select> element in Vue, the fetched data is delayed by one step

I'm currently working on a feature that involves fetching data from a URL that changes every time a user chooses a new value from a <select> dropdown. The fetched data updates the songkickData array with the latest information. However, when I c ...

what is the method to extract the value of a JSON object nested within another JSON object

Can someone please assist me? "_attachments": { "kiran.jpg": { "content_type": "image/jpeg", "revpos": 6, "digest": "md5-mEsoX4ljN1iJlF2bX1Lw2g==", "length": 4601, "stub": true } } I ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...

My goal is to populate all of these elements with Javascript

My goal is to have all the boxes filled with "excellent": https://i.sstatic.net/oHW6W.png let a = document.querySelectorAll('.select2-choice'); a.forEach((e) => {console.log(e)}) a.forEach((e) => {e.innerHTML = ` <span ...

Explore relevant Pill information dynamically based on the image that was clicked in Angular

In this particular situation: Using Angular 1.7.2 Utilizing Bootstrap 3 Encountering some challenges after the user interacts with the image: Current Behavior: Upon clicking any image, a modal window appears displaying relevant content. If image 1 is ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...

I encountered an issue with Material UI tabs showing the error message: "Failed prop type: The prop `children` is not supported. Please remove it."

Recently, I started using Material UI tabs in my project for the first time. Everything seems to be working fine except for one issue that keeps showing up in the console while running the project: Failed prop type: The prop `children` is not supported. Pl ...

Result array, employed as an input for auto-suggest functionality

Iā€™m currently working with an array where I am iterating over an object from an API endpoint that is in stdClass format: foreach($searchResults->hits as $arr){ foreach ($arr as $obj) { $fullType = $obj->_source->categories; print_r($fu ...

Twitter Bootstrap Dropdown PHP link fails to function

Recently, I designed a dropdown menu to be used on a PHP page. The main button, which contains the dropdown links, needs to still function as a link to another page. Despite following all the instructions provided on the Bootstrap website, the main button ...

Angular Material Sidenav fails to cover the entire screen while scrolling

https://i.stack.imgur.com/32kfE.png When scrolling, the Sidenav is not expanding to take up 100% of the screen and it continues to scroll along with the page content. <div layout="column"> <section layout="row" flex> <!-- siden ...