new_new123
new_new123

Reputation: 31

How to pass value from javascript to html

I'm trying to pass value from javascript to html but I can't do it, I used return in js function but probably not correctly

function add() {
  var a3 = document.getElementById('a').value;
  return a3;
}
var a5 = add();
document.getElementById("greeting").innerHTML = a5;
<form>
  a: <input type="number" name="a" id="a"><br>

  <button onclick="add()">Add</button>
  <p id="greeting">Greetings</p>

</form>

Upvotes: 0

Views: 131

Answers (2)

Mamun
Mamun

Reputation: 68933

Your function call is happening way before the click event (on page load), instead of returning the value from function you can update the element's content inside the function itself.

Also, I will suggest you use innerText or textContent to set the content if it is simple string (not htmlString).

You can try the following way:

function add() {
  var a3 = document.getElementById('a').value;
  document.getElementById("greeting").textContent += " " + a3;    
}
<form>
  a: <input type="number" name="a" id="a"><br>

  <button type="button" onclick="add()">Add</button>
  <p id="greeting">Greetings</p>
</form>

Upvotes: 2

Ferin Patel
Ferin Patel

Reputation: 3998

As you are calling add() from html button onClick, you can need to update DOM from add function itself with innerText

function add() {
  var a3 = document.getElementById('a').value;
  document.getElementById("greeting").innerText = a3;
}
a: <input type="number" name="a" id="a"><br>

<button onclick="add()">Add</button>
<p id="greeting">Greetings</p>

Upvotes: 1

Related Questions