Output disappeared Javascript simple innerHTML

2020-04-07 03:51发布

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>

3条回答
Evening l夕情丶
2楼-- · 2020-04-07 04:31

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.

查看更多
【Aperson】
3楼-- · 2020-04-07 04:37

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.

查看更多
太酷不给撩
4楼-- · 2020-04-07 04:43

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()">
查看更多
登录 后发表回答