Value of html text box to be received by javascript variable

0

Hello, I'm learning javascript and wanted to know how I do what is typed in the HTML text box that is printed on the screen in javascript document.write.

    
asked by anonymous 08.03.2017 / 02:20

3 answers

3

You can do this, but using document.write will cause you to rewrite your page, making your controls add up.

function writeItDown(btn){
  var suaVariavel = document.getElementById("txtInput").value;
  document.write(suaVariavel);
}
<input type="text" id="txtInput" /> <button id="myBtn" onclick="writeItDown(this);" >Write</button>

The best option would be to use an html element as a span and write inside it through the innerHTML property of the element. like this:

function escrever(btn){
  var suaVariavel = document.getElementById("txtInput").value;
  document.getElementById('meuTextoVaiAqui').innerHTML = suaVariavel;
}
<input type="text" id="txtInput" /> <button id="myBtn" onclick="escrever(this);" >Write</button>
<br/><span id="meuTextoVaiAqui"></span>
    
08.03.2017 / 02:54
0

You can always do something of the genre:

HTML:

<p>
    //o resultado vai cair aqui
</p>

//com um input
<input type="text" onkeyup="changeResult(this)" />

//ou com uma textarea
<textarea onkeyup="changeResult(this)"></textarea>

JS:

var changeResult = function(element)
{
   document.getElementsByTagName("p") = element.value; 
}

It is possible that there is some error because I did not test but the logic is this

    
08.03.2017 / 03:30
0

Library

<script src="http://code.jquery.com/jquery-1.8.3.min.js"type="text/javascript"></script>

Script

$(document).ready(function() {
      $('.class').keyup(function (e) {
       var v1 = (document.getElementById("v1").value);
       $('#v2').text(v1);
   });
});

HTML

<input type="text" class="class" name="v1" id="v1" size="10" /> 
<span id="v2"> </span>>
    
08.03.2017 / 11:34