how can I add an if with a button

0

hi I try to change the value with a button that is already predetermined, I've been trying with an if and with a function of some condition suggène

<html>
<head>
    <meta charset="UTF-8"/>
    <title>prueba</title>
</head>
<body>
    <button id="pin1" onclick="pin1">numero1</button>
    <input type="button" onclick="Sumar();" value="Calucular">
    <script>
            if  (function pin1){
                var n1 = 81;
            }
            else {
                var n1 = 72;
            }
        }
    var n2 = 21;
    function Sumar() {
            var suma = parseInt(n1) + parseInt(n2);
            alert("La suma es: "+suma)
        }
    
    </script>
</body>
</html>'
    
asked by Davidrj 02.01.2019 в 22:45
source

1 answer

0

As understood in your program by pressing the button number1 you have to change the value of the variable n1 to 81, otherwise it is 72.

Then, when pressing the calculate button you have to add the previous value with the variable n2 that is worth 21 in this case my solution would be the following, using javascript:

  • In the HTML code add the id="nombre" property to both buttons in, and then use it in javascript.
  • Then in javascript:

  • declare a variable and assign the value of the function document.getElementById("nombre_del_id") to import to javascript both buttons.

  • In both variables use the function .addEventListener("click", nombre_de_la_funcion) , it needs two parameters: the name of the event to which they will respond (in this case the click) and the name of the function which they will execute in case of that the previous event occurs. When writing the name of the function do not place parentheses.

  • This way if the button is pressed, javascript will recognize the click that was made to that button and execute the function that we assign to it.

  • And since we defined at the beginning that n1 was 72, Only if the button is pressed the variable n1 will be 81.

  • Then you can press the calculate button and perform the operation with the corresponding value.

  • NOTE: Modify your alert () information a bit so you can notice if there is a change in variable n1 or not.

    var boton_numero1 = document.getElementById("pin1");
    var boton_de_calcular = document.getElementById("boton_calc");
    
    boton_numero1.addEventListener("click", cambio_valor);
    boton_de_calcular.addEventListener("click", Sumar);
    
    var n1 = 72;
    var n2 = 21;
    
    function cambio_valor() {
      n1 = 81;
    }
    
    function Sumar() {
      var suma = n1 + n2;
      alert("La suma de: " + n1 + " + " + n2 + " es igual a " + suma);
    }
    <html>
    <head>
        <meta charset="UTF-8"/>
        <title>prueba</title>
    </head>
    <body>
        <button id="pin1">Numero1</button>
        <input type="button" id="boton_calc" value="Calucular">
    </body>
    </html>
        
    answered by 02.01.2019 в 23:32