Home > Mobile >  Why does my .innerhtml only works for a second?
Why does my .innerhtml only works for a second?

Time:08-27

I am using a form to get a word from a user then displaying it on a web page, here is my js code:

    document.addEventListener('DOMContentLoaded', function() {
        document.querySelector('form').onsubmit = function() {
            const word = document.querySelector('#wrd').value;
            const header = document.querySelector('h1');
            document.querySelector('h1').innerHTML = word;


        }
    });

the word flickers for a second then disappears,can you help me?

CodePudding user response:

You must be submitting more than once while cleaning document.querySelector('#wrd').value if that's the only way to fill document.querySelector('h1'). Also, you might be reloading the page, without looking into your code I can't say for sure. The default behaviour of html submit is to reload the page, which would make it empty and appear to "flick"

CodePudding user response:

When you submit a form it's synchronous by default. It takes the action attribute on the form and tries to post data to it. So in order to prevent that you have to capture the event and prevent its default action.

Take an example below for the different forms.

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('#form1').onsubmit = function() {
    const word = document.querySelector('#wrd').value;
    document.querySelector('h1#first').innerHTML = word;
  }
  
  document.querySelector('#form2').onsubmit = function(e) {
    e.preventDefault();
    const word = document.querySelector('#wrd2').value;
    document.querySelector('h1#second').innerHTML = word;
  }
});
<form id="form1">
  <input type="text" id="wrd" name="content" />
  <button type="submit">Regular Submit</button>
</form>

<h1 id="first"></h1>

<hr>

<form id="form2">
  <input type="text" id="wrd2" name="content" />
  <button type="submit">Submit w/ Default Action Prevented</button>
</form>

<h1 id="second"></h1>

  • Related