Output disappeared Javascript simple innerHTML

瘦欲@ 提交于 2019-12-01 18:02:32

问题


I am new to javascript and on every simple thing i get some kind of problem but this seems un-solve-able to me. I googled and nothing simillar.

After i input data into textbox and store it into variable, i print out variable in paragraph. Problem is that output i printed out disappears within less than second. Code seems to be normal, what might it be? It looks like c when you dont 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>

回答1:


The <form> tag doesn't specify an action attribute, so when you click the submit button, the browser will submit the form to the current URL - which will look a lot like the page is refreshing.

If you want to run the unesi function when the user clicks submit and prevent the HTML form from submitting, you need to change it slightly:

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

The return false prevents the form from submitting itself.




回答2:


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 the function

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

better option is to do it on the form level

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



回答3:


Instead of cancelling the form submitting, 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 it so the form does not try to submit at all when the button is pressed.



来源:https://stackoverflow.com/questions/13765116/output-disappeared-javascript-simple-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!