0

here you can see my code im stuck with trying to input 2 numbers by user in html calling function then adding those 2 in js then printing in html

html.

<html>
  <head>
    <meta charset="utf-8">
    <title> JavaScript | Basics</title>
    <script src="basics.js" charset="utf-8"></script>
  </head>
  <body>
  <!-- <input type="number" name="a" value="0" id="a">
  <input type="number" name="b" value="0" id="b">
  <button type="button" onsubmit="window.alert(a+b)" name="button">j</button>
  < Start JavaScript Here -->
  <form  onsubmit='sum(a,b)'>
  <label for="a">Input number a</label>
  <input type="number" name="a" value="0" id='a'>
  <br>
  <label for="a">Input number b</label>
  <input type="number" name="b" value="0" id='b'>
  <button type="submit" name="submit">Submit</button>
  <output id="total"></output>
</form>
    </body>
</html>

js


// 34343
// window.alert()
function sum(a, b) {
  console.log('hello world');

  var c;
  c.value = parseInt(a) + parseInt(b);
  console.log(c.value);
  window.alert(c.value);
  document.getElementById('total').innerHTML = 'The value of  s ' + c.value;
}

// </script>

help please

SnazzyGill
  • 13
  • 5
  • When you call sum(a,b) on form submit, you haven't defined variables a and b. What does your console say? – mykaf Apr 15 '21 at 17:31

1 Answers1

0

If you only want to sum the two values there is no need to use Form tag.

The Form tag is usually used to send data to a server for processing.

You can read more about Form tag here https://www.w3schools.com/html/html_forms.asp

Using plain JS your code would be something like this:

<html>
  <head>
    <meta charset="utf-8" />
    <title>JavaScript | Basics</title>
    <script src="basics.js" charset="utf-8"></script>
  </head>
  <body>
    <div> <!-- Remove Form-->
      <label for="a">Input number a</label>
      <input type="number" name="a" value="0" id="a" />
      <br />
      <label for="a">Input number b</label>
      <input type="number" name="b" value="0" id="b" />
      <button onclick="sum()" name="submit">Submit</button>   <!-- on click calls sum function-->
      <output id="total"></output>
    </div>
  </body>
  <script>
    function sum() {
      let a = document.getElementById('a').value; // get value from 'a' input
      let b = document.getElementById('b').value; // get value from 'b' input
      console.log('hello world');

      let c = parseInt(a) + parseInt(b); // sum value into 'c' variable

      document.getElementById('total').innerHTML = 'The value of  s ' + c; // adding innerHtml with value of 'c'
    }
  </script>
</html>