Output disappeared Javascript simple innerHTML
Asked Answered
E

3

7

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>
Expeditionary answered 7/12, 2012 at 14:32 Comment(1)
You are submitting the form with the button, try changing type from 'submit' to 'button'Modicum
S
11

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.

Sportscast answered 7/12, 2012 at 14:37 Comment(1)
Thanks for your reply i understand now,and i would not withouth ur explanation. But ur code doesnt do any good its still refresh. Only working thing is removing <form> from code.Expeditionary
W
3

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()">
Weekly answered 7/12, 2012 at 14:36 Comment(1)
I did your first option and still it gets refreshed, as well as second... only thing working was removing <form> from code. thanks a lot i would not understand it without ur help.Expeditionary
B
2

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.

Bankhead answered 7/12, 2012 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.