0

const paragraph = document.querySelector(".paragraph")
const input = document.querySelector("input")

const updInnerHTML = () => {
paragraph.innerHTML = input.value
}
  <form>
    <input type="text" placeholder="Type Something">
    <button onclick="updInnerHTML()">Update InnerHTML</button>
  </form>
  
  <p class="paragraph"></p>

The above code seems to work for a split second, the value appends to the <p> tag and vanishes immediately, Yeah I know this could be made permanent if I remove <form></form> tags, but then I'll lose the ability to automatically clear the input fields! Is there a work around for this? Do I need to use a database or atleast LocalStorage? Is there a way to achieve it without using a database?

  • Does this answer your question? [Submit form without page reloading](https://stackoverflow.com/questions/2866063/submit-form-without-page-reloading) – TYeung Nov 06 '22 at 07:07

2 Answers2

0

Because the button will submit the form which will make the page reload, you can prevent that by setting type="button" to the button element ( type of button by default is submit ).

const paragraph = document.querySelector(".paragraph")
const input = document.querySelector("input")

const updInnerHTML = () => {
paragraph.innerHTML = input.value
}
<form>
    <input type="text" placeholder="Type Something">
    <button onclick="updInnerHTML()" type="button">Update InnerHTML</button>
  </form>
  
  <p class="paragraph"></p>
Mina
  • 14,386
  • 3
  • 13
  • 26
0

use action="javascript:void(0);" for no form submit and then clear form by input.value ='';

const paragraph = document.querySelector(".paragraph")
const input = document.querySelector("input")

const updInnerHTML = () => {
paragraph.innerHTML = input.value;
input.value ='';
}
<form action="javascript:void(0);">
    <input type="text" placeholder="Type Something">
    <button onclick="updInnerHTML()">Update InnerHTML</button>
  </form>
  
  <p class="paragraph"></p>
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33