How to pass data obtained from js to an input of html?

2

Well my question for some will be basic but it turns out that I am doing a program that increases a button pressed, all right up to here, the problem is that

  

I want that increment to be printed in an html input since this   I'm doing it with alerts:

here the code:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>


    </style>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <form class="increment" action="index.html" method="post">

<input type="button" name="" value="contador" onclick="incremen()">

<input type="text" name="" value="" id="resultado">

    </form>

    <script type="text/javascript">
    var contador=0;
function incremen() {


  contador++;
alert(contador);


}


    </script>

  </body>
</html>
    
asked by pintowJD 01.10.2018 в 05:08
source

1 answer

4

Simply instead of doing alert ,

  • you can get the input through your id thanks to the document.getElementById() method
  • later by means of value you assign the incremented value that is to say the value that is stored in variable contador
  • Since you are going to assign the generated value to an input, you must use the value method so that each time you click, it is written in input
  • EXAMPLE

      <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
    
    
        </style>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
    
        <form class="increment" action="index.html" method="post">
    
    <input type="button" name="" value="contador" onclick="incremen()">
    
    <input type="text" name="" value="" id="resultado">
    
        </form>
    <script>
          let contador = 0;
          function incremen(){
            contador++
            document.getElementById("resultado").value = contador
          }
    </script>
    
      </body>
    </html>
        
    answered by 01.10.2018 / 05:16
    source