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

Adding up values of objects in a different array using Vue.js

Recently, I started using VueJs and encountered an object that contains arrays. One of the tasks I need to accomplish is to display the total sum of all amounts in one of the columns of the table. Here is my table structure: < ...

Google Maps is experiencing difficulties maintaining its longitude and latitude coordinates within the Bootstrap tabbed user interface

I implemented ACF's Google Map to display a map on my webpage. I followed the instructions closely and made some minor modifications to the map js for styling purposes. One key change I had to make was in this section to ensure the map loads correctly ...

Is there a way to update a variable in a controller using AJAX?

Is it possible to update a variable in the controller using Ajax? Controller: $basl = array(2018,11,18,0,0); $deger = 3; $baslamatarihi=Carbon::create($basl[0],$basl[1],$basl[2],$basl[3],$basl[4]); $bitistarihi = Carbon::create($basl[0],$basl[1],$basl[2] ...

Creating a task list without using JavaScript in the web browser and without relying on a database

Looking for some guidance on building a todo app for a job interview where JavaScript is disabled in the browser and no database can be used. Any JavaScript needs to be handled on the server side. I have some basic knowledge of node/express and serving H ...

Rendering issues arise in the app when utilizing browserHistory instead of hashHistory with React Router

I have integrated React Router into my current project in the following way: const store = Redux.createStore(bomlerApp); const App = React.createClass({ render() { return ( React.createElement('div', null, ...

What steps should be taken to develop a Hybrid Mobile App concept?

We are currently developing our first hybrid mobile application with a monetizable idea in mind. After conducting some research, it seems that to reach our end goal we will need: A Front End UI Framework: options include Ionic or AngularGap (although d ...

Input the chosen icon list values into a designated box

As a beginner in the world of Javascript, I am venturing into creating a password generator that involves using icons. The concept is simple - by clicking on any number of icons from a list, the corresponding hex code will be displayed in an input box. The ...

getStaticProps function in Next.js fails to execute

My [slug].js file includes two Next.js helper functions, getStaticPaths and getStaticProps. These functions are exported and create the path posts/[slug]. I have also added a post file named hello.json. However, when I try to access localhost:3000/posts/he ...

Conditionality in the ng-repeat directive of AngularJS

Could someone please help with setting a condition in ng-repeat inside a custom directive call? <map-marker ng-repeat='obj in objects' title= 'obj.name' latitude= 'obj.last_point().latitude' longitude= ' ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

Creating and fetching CSV files using PHP and AJAX

I have successfully created a PHP script that generates a CSV file for automatic download by the browser. The code below shows a working version with sample data for different car models. <?php $cars = array( array("Volvo",22,18), array("BMW",15,1 ...

Element sticking on scroll down and sticking on scroll up movements

I am currently working on a sticky sidebar that catches and stays fixed at a certain scroll point using JavaScript. However, I am facing an issue where I need the sidebar to catch when scrolling back up and not go further than its initial starting point. ...

The mouse movement event will not be triggered for every frame when a keyboard event occurs

When the mouse is moving in a browser, ideally the mousemove event should fire every frame. However, if a key is pressed or released (or repeated), the mousemove event stops firing for a frame or two. To test this behavior, you can use the code snippet bel ...

Using v-model to dynamically update the router based on certain conditions

Check out this demo showcasing a navigation menu with nested items. Clicking "more" reveals the expanded list, which can be set to always open using v-model="item.model" with model = true. My goal is to have the submenu stay open only when the user is on ...

Elements that allow for asynchronous data submission without requiring a traditional submit button

Hey there, I could really use some help with this puzzle I'm trying to solve. Here's the situation: <ul> <li>Number: <span id="Number">123</span></li> </ul> I want to set up a connection between t ...

Refreshing AJAX content with a dynamically adjusting time interval

I am facing a scenario where I have a webpage featuring a countdown alongside some dynamic data refreshed via AJAX. To optimize server load, I found a clever solution by adjusting the AJAX refresh interval based on the time remaining in the countdown, foll ...

Struggling with implementing Mobile Navigation menu

I'm struggling to implement a mobile menu for my website. After adding the necessary code, when I view the page in a mobile viewport, all I see are two sets of periods ("..."). However, unlike in the code snippet provided, the list does appear on the ...

What is the most efficient way to optimize the time complexity of a JSON structure?

Here is the input JSON: const data = { "38931": [{ "userT": "z", "personId": 13424, "user": { "id": 38931, "email": "sample", }, } ...

Learn how to obtain a response for a specific query using the `useQueries` function

Can we identify the response obtained from using useQueries? For instance, const ids = ['dg1', 'pt3', 'bn5']; const data = useQueries( ids.map(id => ( { queryKey: ['friends', id], queryFn: () =&g ...

Use ajax to add rows to the second-to-last table

I am facing a situation where I have a table with 25 default rows. When scrolling to the bottom of the table, I want to dynamically insert another set of 25 rows. Everything is functioning correctly, but in a specific scenario, I need to preserve the last ...