javascripthtmlformsinnerhtmlinnertext

I want the innerHTML of my tag to be updated with the input value


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?


Solution

  • 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>