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

React is unable to identify the `isDisabled` attribute on a DOM element within an img tag

After updating my React/Next.js App, I encountered the following issue: Upon investigation, React is indicating that the isDisabled prop is not recognized on a DOM element. To resolve this, you can either specify it as lowercase isdisabled if you want it ...

Looking for a JavaScript regex pattern that matches strings starting with the letter "p" and containing at least

I have recently started learning about JavaScript regular expressions. I attempted the following expression for a string starting with the letter "p" followed by digits: p1749350502 The letter "p" is constant and the remaining digits are variable. Howeve ...

What is the reason for sending a JSON string in an HTTP POST request instead of a JavaScript object in AngularJS

When sending data via a post request in AngularJS, the code may look like this: $http({ method: 'POST', url: url, data: inputParams, headers: headers }) .then(function succes(response) { successCallBack(response.data); } Here is h ...

Embed an external website within a div element

Is there a way to embed an entire external website onto another site, without scroll bars or borders? I attempted this method but the entire page did not load, and there were still scroll bars and borders present. <!DOCTYPE HTML> <html> <b ...

Display the DIV specifically for visitors arriving from Facebook

I want to display a specific DIV on the product page only if the user has visited from Facebook. Currently, I am using the following code to check if they arrived from Facebook: var ref = document.referrer; if (ref.match(/^https?:\/\/([^\ ...

Steps for dynamically executing an Angular ng-include directive in real-time

Is there a way to dynamically insert an ng-include element into an HTML page and have it function properly? I am working on a Drag N Drop application where users can drag an element onto the page, and upon dropping it in the designated zone, the original ...

What is the best way to enlarge text size with jquery?

I am attempting to: $('a[data-text="size-bigger"]').click(function () { a=$('span'); b=$('span').css('font-size'); a.css('font-size', b+1); } ); Initially, I ha ...

Having trouble rendering JSON data on a FlatList component in React Native

After expanding FlatList in console.log and verifying the JSON value, I am facing an issue where the values are not displaying on the list. The data is being passed to the second screen and displayed there, but the first screen remains blank. Any assistanc ...

Issue with React not displaying JSX when onClick Button is triggered

I've recently started learning React and I'm facing a problem that I can't seem to figure out. I have a basic button, and when it's clicked, I want to add another text or HTML element. While the console log statement is working fine, th ...

AngularJS and CodeIgniter collaborating to bring server-side pagination

I am currently working on integrating pagination using AngularJS and CodeIgniter. The current implementation requires fetching all records at once. However, I aim to modify it so that the data can be retrieved one page at a time from the server during run ...

Change the appearance of text with a button click using JavaScript

Currently mastering JavaScript but encountering an issue. How do I change the text to underline when clicking on "Click Me"? <p id="demo" style=" text-decoration:none; ">Hello JavaScript!</p> <button type="button" onclick="document.getE ...

Revamping the hyperlinks in my collapsible menu extension

Is there a way to modify the links in this accordion drop menu so that they lead to external HTML pages instead of specific areas on the same page? I've tried various methods but can't seem to achieve it without affecting the styles. Currently, i ...

Can anyone guide me on creating a Mapbox map layer using React.js?

I'm currently in the process of creating a polygon layer on top of my Mapbox map using ReactMapboxGL. I have some Mapbox Javascript code that I need to convert into React.js format: map.on('load', function () { map.addLayer({ ...

How do I use React and Material-UI to efficiently display multiple tables from a complex JSON object containing multiple arrays of data?

Trying to come up with an innovative approach to generate a unique dynamic table component that can create individual tables based on the number of arrays in a dictionary object (essentially iterating through each array and generating a table). For my sce ...

Vue.JS and its Onclick event handler allows for dynamic and interactive

These are my two buttons: <button onclick="filterSelection('Action')">Action</button> and <button onclick="filterSelection('Adventure')">Adventure</button> Now, I'm trying to achieve the same fun ...

Having trouble with Google Maps Places API autocomplete feature; it's not functioning properly

My goal is to integrate the Google Maps Places API with a search box. To test jQuery autocomplete, I managed to make it work using this simple example: function bindAutocomplete() { var locationSearch = $("input#Location"); locationSearch.autocom ...

Assistance needed with selecting elements using jQuery

After some practice with jQuery, I managed to select this specific portion from a lengthy HTML file. My goal is to extract the values of subject, body, and date_or_offset (these are name attributes). How can I achieve this? Let's assume this snippet i ...

The JavaScript function I created to remove the last item in an array is not functioning correctly when it encounters an "else

My button has been designed to delete the last index from this.fullformula, which is a string. However, I've encountered an issue with deleting characters from this.result, which is an integer. Instead of looping over the function, it only deletes one ...

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

Combine functions from two objects that share the same properties into an array for each property

I need help combining the methods from two objects into one, resulting in an array of methods for each property in the parent object: obj1 = {"prop1":"method1","prop2":"method2"} obj2 = {"prop1":"method3","prop2":"method4"} Expected result: obj1 = {"pro ...