What is the best way to showcase a user's input in a webpage using vanilla javascript

Struggling with creating functionalities for a simple calculator using vanilla.js. Able to display numbers on click but facing issues with multiple clicks and deletion of values. Trying to use addeventlistener but encountering a Type Error "addeventlistener not a function". Any recommended websites or tutorials to improve understanding of vanilla.js? Thank you in advance.

var result = document.querySelector('#result');

var clear = document.querySelector('#delete');

var backSpace = document.querySelector('.backspace');

var numbers = document.querySelectorAll('.input-btn');

var operators = document.querySelector('.operator-right');

var equalBtn = document.querySelector('.equal-btn');

function insert(num) {
  result.value = num;
}

<div class="container">
  <div class="calc">
    <div class="result">
      <input class="input-btn__result" id="result" value="0">
    </div>
    <div class="btns">
      <input class="clear" id="delete" type="button" onClick="clear()" value="C">
      <input class="backspace" type="button" name="" value="<">
      <input class="input-btn__divide operator-right" type="button" name="" value="/">
      <input class="input-btn" type="button" onClick="insert(1)" value="1">
      <input class="input-btn" type="button" onClick="insert(2)" name="" value="2">
      <input class="input-btn" type="button" onClick="insert(3)" name="" value="3">
      <input class="input-btn operator-right" type="button" name="" value="*">
      <input class="input-btn" type="button" onClick="insert(4)" name="" value="4">
      <input class="input-btn" type="button" onClick="insert(5)" name="" value="5">
      <input class="input-btn" type="button" onClick="insert(6)" name="" value="6">
      <input class="input-btn operator-right" type="button" name="" value="+">
      <input class="input-btn" type="button" onClick="insert(7)" name="" value="7">
      <input class="input-btn" type="button" onClick="insert(8)" name="" value="8">
      <input class="input-btn" type="button" onClick="insert(9)" name="" value="9">
      <input class="input-btn operator-right" type="button" name="" value="-">
      <input class="input-btn" type="button" onClick="insert('.')" name="" value=".">
      <input class="input-btn" type="button" onClick="insert(0)" name="" value="0">
      <input class="equal-btn" type="button" name="" value="=">
    </div>
  </div>
</div>

Answer №1

There are several approaches to accomplishing your goal. Instead of seeking recommendations on resources for learning vanilla JS, it's advisable to explore various resources available through a simple Google search and select the one that suits you best. As mentioned by Alvin in their response, understanding addEventListener is crucial.

Here's how I would tackle it utilizing your HTML structure (with one important adjustment: I've removed all instances of the onClick attribute from your HTML - separating JavaScript code from HTML layout is recommended):

const result = document.getElementById('result'),
      btns = document.querySelector('div.btns');

let calculandum = '';

for (let child of btns.children) {
  child.addEventListener('click', insert);
}

function insert(e) {
  let btnValue = e.target.value;
  switch (btnValue){
    case 'C':
      result.value = '0';
      calculandum = '';
      break;
    case '<':
      if (result.value) result.value = result.value.slice(0,-1);
      if (result.value === '') result.value = '0';
      break;
    // Similar cases for other operations omitted for brevity
  } 
}
<div class="container">
  <div class="calc">
    <div class="result">
      <input class="input-btn__result" id="result" value="0">
    </div>
    <div class="btns">
      <!-- Buttons structure here -->
    </div>
  </div>
</div>

This should suffice for handling multiplications, and you can extrapolate this concept for the remaining operations as well. Additionally, the unnecessary vars have been eliminated. It's worth reconsidering how classes are used for HTML elements; while classes are suitable for multiple elements, IDs serve better for individual elements (thus, classes like calc and btns could be changed to IDs).

Answer №2

You have the option to assign a class name specifically for input buttons that are intended for the insert function. Afterwards, you can utilize the addEventListener method to attach events.

var result = document.querySelector('#result');

var clear = document.querySelector('#delete');

var backSpace = document.querySelector('.backspace');

var numbers = document.querySelectorAll('.input-btn');

var operators = document.querySelector('.operator-right');

var equalBtn = document.querySelector('.equal-btn');

var insertBtns = document.querySelectorAll('.insert-btn');

function insert(e) {
  result.value = e.target.value;
}

for (var i = 0; i < insertBtns.length; i++) {
  insertBtns[i].addEventListener('click', insert);
}
<div class="container">
  <div class="calc">
    <div class="result">
      <input class="input-btn__result" id="result" value="0">
    </div>
    <div class="btns">
      <input class="clear" id="delete" type="button" onClick="clear()" value="C" >
      <input class="backspace" type="button" name="" value="<">
      <input class="input-btn__divide operator-right" type="button" name="" value="/">
      <input class="input-btn insert-btn" type="button"  value="1">
      <input class="input-btn insert-btn" type="button" name="" value="2">
      <input class="input-btn insert-bt" type="button" name="" value="3">
      <input class="input-btn operator-right" type="button" name="" value="*">
      <input class="input-btn insert-btn" type="button" name="" value="4">
      <input class="input-btn insert-btn" type="button" name="" value="5">
      <input class="input-btn insert-btn" type="button" name="" value="6">
      <input class="input-btn operator-right" type="button" name="" value="+">
      <input class="input-btn insert-btn" type="button" name="" value="7">
      <input class="input-btn insert-btn" type="button" name="" value="8">
      <input class="input-btn insert-btn" type="button" name="" value="9">
      <input class="input-btn operator-right" type="button" name="" value="-">
      <input class="input-btn insert-btn" type="button" name="" value=".">
      <input class="input-btn insert-btn" type="button" name="" value="0">
      <input class="equal-btn"  type="button" name="" value="=">
    </div>
  </div>
</div>

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

Getting the JavaScript file name within another JavaScript file - a simple guide

Imagine having an HTML file that references two external JavaScript files. One of these JavaScript files contains errors (likely compilation errors), while the other file includes an onerror method without any issues. When you open the HTML file in a brows ...

Increase or decrease values in an input field using Vue3 when typing

I am looking to implement a feature where users can input numbers that will be subtracted from a fixed total of 100. However, if the user deletes the input, I want the difference to be added back to the total of 100. Despite my attempts, the subtraction wo ...

Exploring Laravel's method for retrieving data from multiple tables in the controller

In an effort to make my jQuery call more dynamic, I have a controller with the following method: public function api(Request $request , $project_id){ return Program::where('project_id',$project_id)->get(); } This results in: [{"id":178," ...

Caution: Anticipated the server's HTML to include a corresponding <body> within a <div> tag

Upon checking the console, I noticed a warning message appearing. I am puzzled as to why this is happening since I have two matching <body> tags in my index.js file. The complete warning message reads: Warning: Expected server HTML to contain a matc ...

Creating an array of multiple divs based on numerical input

I am working on a project to show multiple divs based on the user's input number. For example, if the user selects 3, then 3 divs should be displayed. While I have successfully implemented this functionality, I need to dynamically assign IDs to each ...

Exploring the history and present state of Vue lifecycle hooks

Is there a way to access previous and current data in the updated lifecycle hook in Vue, similar to React? I want to be able to scroll a list of elements to the very bottom, but for this I need: The already rendered updated DOM (to calculate the scroll) ...

Stopping form submission on a jQuery form

I am in the process of implementing a password control feature on a login form using jQuery and ajax. This is the current script I have: $(document).ready(function() { $("#login-form").submit(function(e) { var csrftoken = getCookie('csr ...

Is there a way to monitor real-time updates without relying on setInterval or timeout functions?

Currently in the process of building a social network, I am working on fetching live notifications. The current approach involves sending an AJAX request every few seconds using setInterval. The code snippet for this operation is as follows: setInterval ( ...

Adjust the CSS of a dynamically generated jQuery checkbox button in real-time

I am working on a project where I am creating a series of jQuery checkboxes dynamically within a loop. Here is how I am doing it: var checkbox = $('<input>').attr({type: 'checkbox', id: checkbox_id); panel.append(checkbox); panel ...

Highlight particular terms (key phrases) within text contained in a <td> tag

I am currently working on a project and facing a challenge that I am unfamiliar with. My task is to highlight specific keywords within text located inside a <td> element. I cannot manually highlight the keywords as the texts are dynamic, originating ...

Displaying genuine HTML content in a React application using Algolia Instantsearch

After setting up a demo app using React with an Algolia search feature, I uploaded some indices into Algolia. The content consists of raw HTML. Is there a way to display this content as real HTML using Algolia? ...

Maintain the link's functionality even after it's been clicked by utilizing the same

I have a fixed navbar with same-page anchors and I want to keep the link active after it has been clicked and taken to that section of the page. While this is simple for links to another page, I'm struggling to figure out how to do it here. Here&apos ...

Tips for receiving dual return values from an AJAX request

I am sending an array of table IDs to retrieve the table numbers associated with those IDs from the database. I need to add up all the default seats for each table ID and return the total. JAVASCRIPT : function showUser(str) { if ...

Steps to configure npm start for an electron application using "babel-node --presets es2015,stage-3"

I've been experimenting with getting my npm start to work properly for electron. Typically, you would start a non-distributed app with electron . or ./node_modules/.bin/electron .. However, due to my use of NodeJS v8.4.0 and ES6/7 syntax, my npm start ...

Activate on click using JavaScript

When a link with the class .active is clicked, I want to use a JavaScript function to deactivate any other active links. The structure of the code should be as follows: <ul class="product"> <li><a href="#myanmar" class="active">Mya ...

The imgAreaSelect plugin is up and running successfully. Now, I am looking to utilize the x and y coordinates to make updates to the image stored in the database. How can I

After retrieving the dimensions and coordinates from the jQuery plugin imgAreaSelect, I am looking for guidance on how to update the image in my database based on this selection. The database contains a tempImage and Image field, and my goal is to allow ...

Sending cookies via POST/GET request with Credentials is not functioning

Greetings, despite the numerous duplicates of this inquiry, my attempt to solve it has been unsuccessful. Therefore, I am initiating a fresh discussion. Aside from utilizing axios, I also experimented with fetch but encountered similar outcomes. On the b ...

Exploring the power of Angular 2 Directive scopes

When it comes to Angular2, Directives do not come with "scopes", unlike Components. However, in my specific case, I require a Directive to establish a scope. Take a look at my App component - it contains an HTML template, and the foo directive could potent ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

What is the best way to pass compile-time only global variables to my code?

I am looking for a way to easily check if my code is running in development mode, and based on that information, do things like passing the Redux DevTools Enhancer to the Redux store. I know I can use process.env.NODE_ENV for this purpose, but I find it ...