Can the client enter variables from his browser? (JavaScript)

0

In all the examples that I have seen, it always defines the variables in the document, it never allows the client to enter their data. I can only use JavaScript, I can not use PHP. If necessary I can add some HTML tag. Here is an example:

<html>
<head>
    <title>Ejemplo variables</title>
    <script type="text/javascript">
        var variable1;
        var variable2;
        /* Lo que quiero es que estas variables las introduzca una tercera 
        persona desde un navegador ya que en la mayor parte de ejemplos los 
        hacen de la siguiente forma "var= variable3="Hola";" La idea sería 
        similar a rellenar un formulario para que finalmente te saltase un 
        cuadro modal con toda la información rellenada. */
        alert(variable1+variable2)
    </script>
</head>
<body>
    /* Si es necesario aquí se podría introducir lo que sea, como un botón 
    por ejemplo. */
</body>
</html>

Is this possible? Thank you very much!

    
asked by J.Adell 28.02.2018 в 12:49
source

2 answers

4

You have several ways to do it. The first and the simplest is to use the prompt () method that shows a window where you can enter information and process it.

var variable1 = 10;
var variable2;

variable2 = window.prompt('Introduce un numero: ');

//Convertimos en entero la cadena introducida para poder sumar enteros
var suma = variable1 + parseInt(variable2);

document.body.innerHTML = suma;

Another way, a little more complex, is through a form. In this case if you would have to add more tags to your html to be able to execute it. It would be using a input text type and taking the value of that input by handling the DOM , obtaining the value of the text with the method document.getElementById().value and use it to perform the operation.

function suma() {
    var variable1, variable2, resultado;
    
    variable1 = 10;

    //Coges el valor del cuadro de texto mediante su ID y el atributo value
    variable2 = document.getElementById("variable2").value;

    resultado = variable1 + parseInt(variable2);
    
    document.getElementById("resultado").innerHTML = resultado;
}
<p>Variable 1 = 10</p>
<p>Introduce la variable 2:</p>

<input type="text" id="variable2">

<button type="button" onclick="suma()">Suma</button>

<p id="resultado"></p>
    
answered by 28.02.2018 / 13:20
source
1

You can do it perfectly. For this you would basically need two things:

  • Add what is called an eventlistener or event listener . That is, declare in JS something like I want this code to be executed when this event occurs . An event can be: when the DOM is fully loaded, when a button is pressed, when it is written in an input, etc.
  • Within that listener you define the code to be executed. In general, you get values that exist in the DOM by using document.getElementById or other means.
  • Here is an example with several listeners .

    /*
      *Este listener se suele poner siempre al principio 
      *para que no se intente usar nada del DOM 
      *sin que éste esté cargado.
      *Todas las demás funciones suelen dentro de este bloque
     */
    document.addEventListener("DOMContentLoaded", function(event) {
      var elInput = document.getElementById("myInput");
      var variable1 = "Definida en JS";
      var variable2 = elInput.value;
      console.log(variable1 + " y " + variable2);
    
      /*Agregamos un listener para cada vez que se escriba algo en el input*/
      elInput.onkeyup = function() {
        var variable2 = elInput.value;
        console.log(variable1 + " y " + variable2);
      };
      
      /*Agregamos un listener para el botón*/
      var btnEnviar = document.getElementById("btnEnviar")
      btnEnviar.onclick = function() {
        var variable2 = elInput.value;
        console.log(variable1 + " y " + variable2);
      };
    
    });
    <input id="myInput" type="text" placeholder="Escribe algo aquí" value="Texto de prueba" />
    <button id="btnEnviar">Enviar</button>
        
    answered by 28.02.2018 в 13:16