When a list item is clicked, extract its innerHTML and pass it to a JavaScript

Hey there, I've created a basic HTML/JavaScript calculator.

Each time I perform a calculation, it gets added to the list shown on the webpage.

Here's what I'm looking for: When a user clicks on an item in the list, I want to retrieve the string of that operation so I can reload the values back into operand 1 and operand 2.

<html>
<head>
</head>
<body>
    <h1>Calculator With Buttons And History</h1>
    <table>
    <tbody>
    <tr>
    <td><label>Operand 1:</label></td>
    <td><input id="o1" type="text" /></td>
    </tr>
    <tr>
    <td><label>Operand 2:</label></td>
    <td><input id="o2" type="text" /></td>
    </tr>
    </tbody>
    </table>
    <p><button onclick="add()"> + </button> <button onclick="sub()"> - </button> <button onclick="mul()"> x </button> <button onclick="div()"> / </button></p>
    <p>Result:<input id="result" name="result" readonly="readonly" type="text" value="" /></p>
    <ul id="result_list" class="list-group" onclick="getCalc(this)">
        <li class="list-group-item">1+1=2</li>
        <li class="list-group-item">1-1=0</li>
        <li class="list-group-item">2*2=4</li>
        <li class="list-group-item">3/3=1</li>
      </ul>
    <script src="filter.js"> </script>
    <script src="calc.js"> </script>
</body>
</html>

Answer №1

If you're looking to fetch innerHTML without viewing the code, there are a couple of ways to approach it:

One option is to remove the onClick event from the <ul> tag and add it to each individual <li> item:

<ul id="result_list" class="list-group">
   <li class="list-group-item" onclick="getCalc(this)">1+1=2</li>
   <li class="list-group-item" onclick="getCalc(this)">1-1=0</li>
   <li class="list-group-item" onclick="getCalc(this)">2*2=4</li>
   <li class="list-group-item" onclick="getCalc(this)">3/3=1</li>
</ul>

In your JavaScript, you can then define the getCalc function like this:

 function getCalc(item) {
    console.log(item.innerHTML)
 }

Another approach is to add an eventListener for

<ul id="result_list" class="list-group">
:

<ul id="result_list" class="list-group">
   <li class="list-group-item">1+1=2</li>
   <li class="list-group-item">1-1=0</li>
   <li class="list-group-item">2*2=4</li>
   <li class="list-group-item">3/3=1</li>
</ul>

And in your JavaScript file, you can set up the event listener like this:

const resultList = document.getElementById('result_list');
 resultList.addEventListener('click', item => {
    console.log(item.target.innerHTML);
 });

Answer №2

To implement this using pure JavaScript, you must update your add and sub functions to include event listeners for the li elements they generate:

<html>
<head>
</head>
<body>
    <h1>Calculator With Buttons And History</h1>
    <table>
    <tbody>
    <tr>
    <td><label>Operand 1:</label></td>
    <td><input id="o1" type="text" /></td>
    </tr>
    <tr>
    <td><label>Operand 2:</label></td>
    <td><input id="o2" type="text" /></td>
    </tr>
    </tbody>
    </table>
    <p><button onclick="add()"> + </button> <button onclick="sub()"> - </button> <button onclick="mul()"> x </button> <button onclick="div()"> / </button></p>
    <p>Result:<input id="result" name="result" readonly="readonly" type="text" value="" /></p>
    <ul id="result_list" class="list-group">
      </ul>
</body>
<script>
  const o1 = document.querySelector("#o1");
  const o2 = document.querySelector("#o2");
    
  const resetOperators = (e) => {
    const re = /\+|\-/;
    const [v1, v2] = e.target.innerText.split(re);
    o1.value = v1;
    o2.value = v2
  }

  const add = () => {
    const val = parseFloat(o1.value, 10) + parseFloat(o2.value, 10);
    const li = document.createElement("li");
    li.innerHTML=`${o1.value}+${o2.value}`;
    li.addEventListener("click", resetOperators);
    document.querySelector("#result_list").appendChild(li);
    document.querySelector("#result").value = val;
  }
</script>
</html>

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

I'm having trouble with certain JavaScript functions on my website - some are working fine, but others aren't. Any suggestions on what I should do

I just finished developing a calculator using HTML, CSS, and Javascript. It works flawlessly for all numbers 1 through 9 and the operators +, -, *, /, and %. However, I am facing issues with the number 0, C, and = buttons not functioning properly. Upon in ...

Multiple file formats supported by Uploadify

I am trying to find a solution for having various file types in the jQuery plugin Uploadify. Consider this scenario: You want to open a file with a program of your choice. Starting with a default OS dialog, you can select different file types from a dropd ...

I encounter an error message stating "The requested resource has been deleted" whenever another website links to my site

Having recently started working with Angular and Azure setups, I am facing an issue with a simple jade login form that posts to a URL (different origin than my website) upon submission. As a security measure, I have replaced the actual URL with a sample on ...

Issue with improper lighting on Three.Geometry objects when using LambertMaterial in Three.js

After enhancing my initial version of this inquiry (previously asked question) with a JSFiddle showcasing the latest build of Three.JS and illustrating the lighting issue on Three.Geometry, I encountered difficulties with dependencies in Stack Snippets. Ho ...

Ways to transform the DropBox chooser button into an image

I'm looking to incorporate an image in place of Dropbox's default chooser button. Despite reviewing their API documentation, I haven't come across any methods to use alternative elements for the Dropbox chooser. Does anyone have a solution f ...

Issue encountered when trying to add data into MySQL database

Having trouble inserting data into my MySQL database, even though I believe I'm doing it correctly. Does anyone know how to troubleshoot this issue or if I may have overlooked something? Everything seems to be working fine, but for some reason, it&apo ...

Invoke a JavaScript function once the div has finished loading

After clicking on a radio button, I am dynamically loading a div element. I want to hide a specific part of the div once it is loaded. $(function($) { $('.div_element').on('load', function() { $('.textbox').hide(); } ...

utilizing a modal to trigger a function within the parent scope of an Angular application

I have a main.controller.js where there is a modal in place to notify the user of a warning before proceeding to the rest of the application. For example, I want to trigger my fileNew function from the modal. In main.controller.js: $scope.warningMod ...

Adhesive Navigation Bar

Check out this link: JSFIDDLE $('.main-menu').addClass('fixed'); Why does the fixed element flicker when the fixed class is applied? ...

jQuery Update for Header/Footer Navigation

I have implemented header and footer navigation with different states using jQuery. However, I am encountering an issue when trying to update the header nav upon clicking on the footer nav items. Specifically, I want the header nav to reflect the same sele ...

Encountered a TypeError in React 16.7: The function (0, _react.useState) is not recognized

Error: TypeError: (0 , _react.useState) is not a function React versions currently being used: "react": "^16.7", "react-dom": "^16.7", File src/App.js: import {memo, useState} from 'react' export default memo(() => { useS ...

Utilizing Vue.js to create a secondary navigation by transforming a select dropdown and integrating tabs simultaneously

After successfully setting up a tabs navigation using Vue with the help of a previous question HERE, I now have a working code for the tabs navigation as shown below: <ul> <c:forEach items="${tabnav.tabs}" var="tab" varStatus="loop"> <c:i ...

Why is Vue JS throwing an error stating "undefined is not an object"?

After creating a Vue app on a single page .html file served by django, which consists of multiple components, I decided to transition this project into a full-fledged Vue.js project using the Vue CLI. Initially, I thought it would be a simple task to trans ...

Remove properties that are not part of a specific Class

Is there a way to remove unnecessary properties from the Car class? class Car { wheels: number; model: string; } const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'}; const goodCar = filterUnwant ...

Jquery form calculation not matching up

I've been struggling to make this jQuery math function work with my form. The snippet works fine, but when I try to integrate it into the actual form, I can't seem to get it aligned properly to perform the required calculations. Any suggestions ...

Attempting to implement Vue js extensions without relying on NPM or webpack

The issue Currently, I am trying to follow the jqWidgets guidelines provided in the link below to create a dropdown box. However, the challenge I'm facing is that their setup involves using the IMPORT functionality which is restricted by my tech lead ...

React: The issue with async and await not functioning as expected when using fetch

I am working with an API on a Node server that returns JSON data like this: {"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuan ...

Efficiently Displaying Multiple HTML Elements in React Native WebView

I am currently working on developing an Epub reader in React Native and facing a challenge. I need to find a way to efficiently transfer multiple html content files from the Epub container to the webview in order to achieve seamless pagination. ...

Show the text from the chosen option using jQuery with a button

Hey everyone, I have a question regarding a coding issue I'm facing. In this problem, I am unable to display the text from the selected option when I click the order button. The desired result is to show the selected option that I choose and display i ...

JavaScript function to toggle visibility and scroll back to top of the page

I have been an avid reader on this platform, and I am hoping that my question has not already been addressed. I am struggling to find a solution to a problem I am facing. There are two DIVs in my code that I toggle between showing and hiding using Javascr ...