0

I want to take the value of a text box and put it with a variable, then print the value of the variable as text on the page when a button is pressed. I'm using JavaScript and not using the form tag. So, how do I do this with what I have?

my code:

var x = document.getElementById("I1");
var y = document.getElementById("I2");
var z = x+y;

document.getElementById("B2").onclick = function myFunction2(){
  documen.getElementById("H2").innerHTML = x;
}
falinsky
  • 7,229
  • 3
  • 32
  • 56
  • You'll need to show your "*[mcve]*" HTML code for this question, in addition to the JavaScript (incidentally, you've got `documen` instead of `document`, which is a syntax error). As a new contributor you may also benefit from reading the "*[ask]*" guidance. – David Thomas Aug 29 '18 at 21:33
  • Possible duplicate of [How do I get the value of text input field using JavaScript?](https://stackoverflow.com/questions/11563638/how-do-i-get-the-value-of-text-input-field-using-javascript) – inorganik Aug 29 '18 at 21:39

4 Answers4

0

If I understand you correctly, you'll simply want to grab the .innerHTML from your <textarea>, and assign that to x. Also note that you have documen instead of document inside of your click function.

Note that you're probably also looking to output z rather than x. This will only work (the way you expect) if both x and y are integers, so it's also a good idea to run parseInt() over the two values.

Here's a working example:

var x = parseInt(document.getElementById("I1").innerHTML);
var y = parseInt(document.getElementById("I2").innerHTML);
var z = x + y;

document.getElementById("B2").onclick = function myFunction2() {
  document.getElementById("H2").innerHTML = z;
}
<textarea id="I1">1</textarea>
<br />
<div id="I2">2</div>
<br />
<button id="B2">Button</button>
<br />
<br />
<div id="H2"></div>
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

Are I1 and I2 the ids of your textbox? because to get the inside text you need to use

var x = document.getElementById("I1").value;
Adan Sandoval
  • 436
  • 1
  • 6
  • 18
0

You should rely on the value attribute of the textarea instead of its innerHTML attribute, and fetch that in the click event handler of the button.

   

    document.getElementById("B2").onclick = function() {
     var x = document.getElementById("I1").value;
 document.getElementById("H2").innerHTML = x;
    }
<textarea id="I1">1</textarea>
<br />
<button id="B2">Button</button>
<br />
<br />
<div id="H2"></div>
ThS
  • 4,597
  • 2
  • 15
  • 27
0

document.getElementById("B2").onclick = function myFunction2(){
 var x = Number(document.getElementById("I1").value);
 var y = Number(document.getElementById("I2").value);
 var z = x+y;
  document.getElementById("H2").innerHTML = z;
}
<input type="text" id="I1" value="" /> + 
<input type="text" id="I2" value="" /> = 
<button id="B2">
?
</button>
<span id="H2">
</span>
khoekman
  • 1,153
  • 7
  • 16