Executing Enter Key and Button Simultaneously with JavaScript: Step-by-Step Guide

I need assistance understanding how to simultaneously trigger the enter key and button in this code. When the value is entered into the input field, it should trigger both the enter key and the button "Enter" at the same time. Additionally, after pressing the button, the input field should clear each time.

<div id="myForm">
  <input type="text" id="bedrag" />
  <button type="button" onclick="check_field('bedrag');" value=''>Enter</button>
  <p>Your total:</p>
  <p id="result"></p>
</div>
<script>
  var total = 0;
  var amount = document.getElementById("bedrag");
  amount.onkeydown = calculate

  function calculate(e) {
    if (e.keyCode == 13) {
      var enteredAmount = +document.getElementById("bedrag").value;
      total = total + enteredAmount;
      document.getElementById("result").innerHTML = 'The amount is ' + total;
    }
  }

  function check_field(id) {
    var field = document.getElementById(id);
    if (isNaN(field.value)) {
      alert('not a number');
    } else {
      return myFunction();
    }
</script>

Answer №1

There are two key points you need to consider:
- First, identify common code that can be used for both clicking a button and pressing the Enter key, then consolidate it into a single function,
- Second, remember that your input will always be a string, so you must use parseInt to convert it in order to perform addition operation

Check out this functional example:

<div id="myForm">
  <input type="text" id="amount" />
  <button type="button" onclick="validate_field('amount');" value=''>Enter</button>
  <p>Your total:</p>
  <p id="result"></p>
</div>
<script>
  var total = 0;
  var amount = document.getElementById("amount");
  amount.onkeydown = calculate;

  function submit() {
    var enteredAmount = document.getElementById("amount").value;
    if (isNaN(parseInt(enteredAmount))) {
      alert('not a number');
    } else {
      total = total + parseInt(enteredAmount);
      document.getElementById("result").innerHTML = 'The total is ' + total;
    }
  }

  function calculate(e) {
    if (e.keyCode == 13) {
      submit();
    }
  }

  function validate_field(id) {
    submit();

    // Clearing the input field after clicking the button
    document.getElementById(id).value = "";
  }
</script>

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

Problem with the $http module in Angular 1.2

Recently, I started incorporating Angular 1.2.0 into my development application and encountered an issue with a particular function not working as expected: var myItems = angular.model('myItems', []); myItems.controller('itemsController&ap ...

Incorporating the values of JavaScript objects into a global variable

I'm currently developing a bank account program and facing a challenge in adding my direct debits (DDs) into the global variable. When I create new objects using my constructor function and add them into the bank account, only the last created DD is s ...

Trouble arises with Webpack during the compilation of JavaScript files

I've been tackling a project in Laravel 5.3, smoothly using webpack until I decided to configure ES6 by adding babel packages to my npm module. This caused a code breakdown, prompting me to revert back to the initial setup. However, now every time I m ...

extracting key-value pairs from nested arrays in javascript objects

As a beginner in javascript, I am facing an issue that may seem basic to others. Here is the json data I am working with: { "statusCode": 200, "status": "success", "data": [ [ { "city": "Alexandria", ...

Encountered a problem while attempting to remove node version

When I run the command nvm ls -> v4.3.2 system default -> 4.3.2 (-> v4.3.2) node -> stable (-> v4.3.2) (default) stable -> 4.3 (-> v4.3.2) (default) iojs -> N/A (default) Upon running nodejs --version, it returns v0 ...

Creating stunning light effects with camera flash using three.js

I'm working on a website using the amazing three.js library. My current challenge is figuring out how to incorporate a camera flash effect into three.js. Currently, I have a rotating cube in my scene and I would like to have a camera flash occur after ...

Add a static line of names to a JavaScript file

Looking for a way to generate data with the following javascript snippet: for (var l = 0; l < table.length; l +=1) { fs.appendFile('results/Test'+ username +'.csv', var1+i, var2 , function(err) { if(err) { return c ...

Guide on integrating React.js into an HTML development webpage

I can't seem to get this code to work properly. I have saved it as an .html file on my computer, but it's not displaying anything when I try to open it in Google Chrome. <DOCTYPE! html> <html> <head> <script src= ...

Error in Uploading Files with AngularJS - Uncaught SyntaxError: Unexpected token

I'm having trouble uploading an image file using Angular and PHP, specifically at the app.service Error line: app.service('fileUpload', ['$https:', function ($https:) { Code app.service('fileUpload', ['$https:&ap ...

Showing fixed values inside directive view after successful injection

Looking for some answers about using constants in angularjs. Here are the constants defined in my app.js: ... angular .module('blocTime', ['firebase', 'ui.router']) .config(config) .constant(&apos ...

Error encountered with select2 when using a remote JSONP dataset

When attempting to query the Geonames data using select2, everything seems to work fine with formatting the results. However, an error occurs once the results are populated, which I suspect is preventing the formatSelection function from running properly. ...

Deleting an entry from a JSON file by comparing keys within the same array using the jq tool

I am working with a JSON file containing quiz questions. The format of the questions is as follows: { "ques": "What is the meaning of life?", "ans": "42", "Option1": "123", "Option2": "456", "Option3": "789", "Option4": "42" } { "ques": "Wha ...

PHP variable not receiving Ajax variable

As a beginner in Ajax and jQuery, I am learning through Stack Overflow and online tutorials. Please be considerate of my novice level as you read and potentially offer advice on my post. I have successfully created a form that displays a message upon subm ...

Issue with PLUploader in ASP.Net/JQuery: "Add Files" button not functioning post image upload操作

Hello, I've been utilizing the PLUploader controller for ASP.NET in C#. Initially, it works as intended, but after uploading files, the "add files" button becomes disabled or stops working, preventing me from adding more images. Can anyone offer assi ...

Guide to Binding a JSON Property (Set or Array) to an Interactive Input Form in AngularJS

My input form is structured like this: <div> <div class="form-group"> <label for="inputQuestion" class="col-sm-2 control-label">Question</label> <div class="col-sm-10"> <input data-ng-model="publication.qu ...

When using NodeJS with expressJS, remember that req.body can only retrieve one variable at a

I'm having trouble with my login and signup pages. The login page is working correctly, but the signup page is only transferring the password for some reason. App.JS: var express = require("express"); var app = express(); var bodyParser = require("bo ...

The Render function in ReactJS is not getting refreshed

My goal is to implement a chat feature using material UI. I have set up a function where users can submit new chat messages, which then go through the reducer and are stored in the redux store. The process seems to be working fine, except for the fact that ...

Changing the name of a file using NPM

Is there a way to change the name of a specific file in npm scripts? I need to modify files for distribution, but they must have different names than the original... I attempted using orn, however it only works on the command line and not as an npm script ...

Creating an element in react-draggable with two sides bound and two sides open - here's how!

At the moment, I am facing an issue where the element is restricted from moving outside of the container with the class of card-width-height. My goal is to have the right and bottom sides bounded within the container while allowing the element to move beyo ...

The route path consists of data that will be retrieved before entering the route

I am facing an issue with my router configuration. I have a dynamic Route that requires the last part of its path to be set after fetching data from a store call in beforeRouteEnter. beforeRouteEnter (to, from, next) { if(to.params.categoryId) { next(vm ...