Home > Software design >  I want the innerHTML of my tag to be updated with the input value
I want the innerHTML of my tag to be updated with the input value

Time:11-06

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 ></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?

CodePudding user response:

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 ></p>

CodePudding user response:

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 ></p>

  • Related