Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating HTML elements in Javascript

I am new to JS , and i was creating a form where i would click the save button and the entered text would shown in the page , but when i click the save button the change is shown for a sec and disappears.

Source Code :

function save(){
    save_element = document.getElementById("input_element").value;
    console.log(save_element);
    document.getElementById("saved_text").innerText += save_element;
}
<html>
    <head>
        <title>
            Practising JS
        </title>
    </head>
    <body>
        <form action="">
            Name: <input type="text" placeholder="Enter a Text" id = "input_element">
            <br>
            <button id = "ds" onclick="save()">SAVE</button>
            <h1 id = "saved_text"></h1>
            <script src="./index.js"></script>
        </form>
    </body>
</html> 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The default behaviour of the <form> is to submit the form data to server. You need to prevent this default behaviour by using preventDefault.

function save(event) {
  event.preventDefault(); // Skip default behaviour
  const save_element = document.getElementById("input_element").value;
  console.log(save_element);
  document.getElementById("saved_text").innerText += save_element;
}
<html>

<head>
  <title>
    Practising JS
  </title>
</head>

<body>
  <form action="">
    Name: <input type="text" placeholder="Enter a Text" id="input_element">
    <br>
    <button id="ds" onclick="save(event)">SAVE</button>
    <h1 id="saved_text"></h1>
    <script src="./index.js"></script>
  </form>
</body>

</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading