Home > database >  How to pass value from javascript to html
How to pass value from javascript to html

Time:10-21

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related