Estoy tratando de hacer una calculadora simple, que suma 2 números con solo presionar un botón. He terminado la parte de HTML, pero no tengo ni idea de cómo hacer que el botón agregue los números. Intenté usar el detector de eventos, pero probablemente me faltaba algo. Si puede, escriba el script mientras explica las líneas de código más importantes. ¡Gracias!
<html> <head> <title>A calculator... I guess?</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="main"> <div class="container" style="margin: 100px 200px 0 200px"> <!-- Inputs --> <p>1st number</p> <input type="number" id="one"> <p>2nd number</p> <input type="number" id="two>"> <!-- Button --> <br> <br> <button id="add">Calculate</button> <!-- Result --> <p>Result</p> <input type="text" id="result"> </div> </div> <script> </script> </body> </html><html> <head> <title>A calculator... I guess?</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="main"> <div class="container" style="margin: 100px 200px 0 200px"> <!-- Inputs --> <p>1st number</p> <input type="number" id="one"> <p>2nd number</p> <input type="number" id="two"> <!-- Button --> <br> <br> <button id="add" onClick={calculate()}>Calculate</button> <!-- Result --> <p>Result</p> <input type="text" id="result"> </div> </div> <script> var elementOne =document.getElementById('one'); var elementTwo =document.getElementById('two'); function calculate(){ one = parseInt(elementOne.value) two = parseInt(elementTwo.value) document.getElementById('result').value = one + two; } </script> </body> </html>El script es muy fácil, ¿eres nuevo en JS? El guión está aquí abajo con la explicación que pediste:
//create the function which will run on button click function calculate() { var firstNumber = document.getElementById("one").value; //Get the value of the first input and store it in firstNumber variable var secondNumber = document.getElementById("two>").value; //Get the second one's now firstNumber = parseInt(firstNumber); //Convert both variables from string to integer for we get variables if string datatype when getting the value from an input secondNumber = parseInt(secondNumber); var result = firstNumber + secondNumber; //Add the 2 numbers and store the result in a variable document.getElementById("result").value=result; //Print the "result" variable in the input you want it to get printed in } <html> <head> <title>A calculator... I guess?</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="main"> <div class="container" style="margin: 100px 200px 0 200px"> <!-- Inputs --> <p>1st number</p> <input type="number" id="one"> <p>2nd number</p> <input type="number" id="two>"> <!-- Button --> <br> <br> <button id="add" onclick="calculate()">Calculate</button> <!--Onclick attribute determines the function to run on click of the element the attribute is in--> <!-- Result --> <p>Result</p> <input type="text" id="result"> </div> </div> <script> </script> </body> </html>Adapté tu html para que contuviera un formulario. Los formularios se utilizan para la interacción del usuario, como ingresar números.
<html lang="en"> <head> <title>A calculator... I guess?</title> <script src="AddScript.js" rel="script"></script> </head> <body> <div class="main"> <div class="container" style="margin: 100px 200px 0 200px"> <form > <!-- Inputs --> <label for="one">1st number</label><br> <input type="number" id="one" > <br> <label for="two">2nd number</label> <br> <input type="number" id="two"> <!-- Button --><br> <br> <button id="add">Calculate</button> <br> <br> <!-- Result --> <label for="result">Result</label><br> <input type="text" id="result"> </form> </div> </div> </body> </html>y el javascript. Necesitas usar Number() para convertir el texto a enteros
window.onload = init function init(){ const button = document.getElementById("add") button.addEventListener("click", addTwoNumbers) } function addTwoNumbers(e){ e.preventDefault() const one = document.getElementById("one") const two = document.getElementById("two") const totalSum = Number(one.value) + Number(two.value) const result = document.getElementById("result") result.value = totalSum }