简体   繁体   中英

Several functions

I'm trying to do two functions here, one where I use addition and one where i use multiplication. If i were to type in 5 and 6 the calculate button would generate 11 and 30. Should i put the multiplication function in this one, or a separate one? And if so, how do i connect it to that one button?

 function calculate() { tal1 = document.getElementById("tal1").value; tal2 = document.getElementById("tal2").value; var answer; answer = tal1 * 1 + tal2 * 1; document.getElementById("answer").value = answer; } 
 <form id="f1" name="f1"> <input id="tal1" type="text"><br><br> <input id="tal2" type="text"><br><br> <input onclick="calculate()" type="button" value="Calculate!"><br><br> <input id="answer" type="text"><br><br> <input id="answer" type="text"> </form> 

You could use a single function for calculating both values.

  • Use declared variables on top,
  • take unary plus + for converting string to number
  • use logical OR || for string who are converted to NaN with value zero, have a look to truthy and falsy values, too,
  • take unique id for addressing an element,
  • assign the calculation to the result elements,
  • take a <button> element with an event for calculation and type="button" , otherwise the button works as submit.

 function add(a, b) { return a + b; } function multiply(a, b) { return a + b; } function calculate() { var tal1 = +document.getElementById("tal1").value || 0, tal2 = +document.getElementById("tal2").value || 0; // ^ unary plus, get a number // ^^^^ check for truthyness, take // zero if the first operand // is falsy, like NaN document.getElementById("sum").value = add(tal1, tal2); document.getElementById("product").value = multiply(tal1, tal2); } 
 <form id="f1" name="f1"> <input id="tal1" type="text"><br><br> <input id="tal2" type="text"><br><br> <button onclick="calculate();" type="button">Calculate!</button><br><br> <input id="sum" type="text"><br><br> <input id="product" type="text"> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM