0

I want to sum 2 input values ​​but in one form with JavaScript, like this image:

This

then the output will be 350. is this possible?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 1
    Yes, it's possible. Use `value.split('+')` to get the two parts into an array. Convert each array element to a number, and add them. – Barmar Mar 29 '23 at 23:34
  • 1
    Be more specific about the expected behavior. Do you want the sum "350" to replace the values in the input field, or output it somewhere else? And do you want the sum to be calculated as the user types, when a button is pressed, or when the form is submitted? – Dennis Kats Mar 29 '23 at 23:42

1 Answers1

0
const sum = value
  .split('+')
  .map(value => Number(value))
  .reduce((agg, val) => agg + val, 0);

Where value is the value from your form. This will also work for longer chains and with or without spaces, like 1 + 2+3.

Christian Fritz
  • 20,641
  • 3
  • 42
  • 71