The output is gone Javascript simple innerHTML

I am new to javascript, and on every simple thing I get some kind of problem, but it seems incomprehensible to me. I googled and nothing simillar.

After entering the data in the text field and saving it in a variable, I will print the variable in the paragraph. The problem is that the output I printed out disappears in less than a second. The code seems normal, what could it be? This is like c when you do not put getch (); Thanks in advance.

<form>Unesite broj koji ce se ispisat kasnije.<br> <input type="text" id="userInput"> <input type="submit" name="unos" value="Unesi i ispisi" onclick="unesi()"><br><br> </form> <br><br> <p>Unjeli ste <b id="ispis"></b></p> <script> function unesi(){ var userInput = document.getElementById('userInput').value; document.getElementById('ispis').innerHTML = userInput; } </script> 
+4
source share
3 answers

The <form> does not indicate an action attribute, so when you click the submit button, the browser submits the form to the current URL, which will look very much like a refreshing page.

If you want to run the unesi function when the user clicks the submit button and prevents the HTML form from being unesi , you need to slightly modify it:

 <input type="submit" name="unos" value="Unesi i ispisi" onclick="unesi(); return false;"> 

return false prevents the form from submitting.

+4
source

Because the form submits and refreshes the page. Cancel the form request.

 <input type="submit" name="unos" value="Unesi i ispisi" onclick="return unesi()"> 

and function

 function unesi(){ var userInput = document.getElementById('userInput').value; document.getElementById('ispis').innerHTML = userInput; return false; } 

the best option is to do it at the form level

 <form action="#" method="get" onsubmit="return unesi()"> 
+1
source

Instead of canceling form submission, another option is to change

 <input type="submit" name="unos" value="Unesi i ispisi" onclick="unesi()"> 

to

 <input type="button" name="unos" value="Unesi i ispisi" onclick="unesi()"> 

This will make the form not try to submit at all when the button is clicked.

+1
source

All Articles