Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function prints .innerHTML but HTML only appears for a moment before vanishing

I've got a button that calls a javascript function named "submit()". In that function I simply write document.getElementById('try').innerHTML="it worked"; to test out whether or not my button is passing data to the function or not.

The problem is "it worked" gets printed for about a half second before disappearing.

I made an entire form that printed processed data to the webpage perfectly using the same html page. The only difference is that I changed the structure of my form and moved my functions to a .js file.

Although now, even if I comment out the submit() function in the .js file and paste the function within the core html file the same thing happens. I can paste is above or below the form and the same thing results.

Here is my HTML:

<div class="formsection">
            <button type="Submit" onclick="Submit()">Submit</button>
        </div>
    </form>
</div>
<div id="output">
<p> Try this: <span id="try"></span></p>
</div>

Here is my javascript function:

<script type="text/javascript">
function Submit(){
document.getElementById("try").innerHTML="It worked";   
}
</script>
like image 274
Nick Res Avatar asked Dec 27 '22 08:12

Nick Res


2 Answers

you are using submit button to test your code, it executes the JS code and submitted the form.

If you don't want the form to be submit use return false in submit()

<script type="text/javascript">
function Submit(){
document.getElementById("try").innerHTML="It worked";   
return false;
}
</script>

and in html again use return

<button type="Submit" onclick="return Submit()">Submit</button>

In javascript when any event handler returns false that halts the event execution.

like image 173
Naren Sisodiya Avatar answered Apr 09 '23 18:04

Naren Sisodiya


The issue you're experiencing is due to your markup, mainly this piece:

<button type="Submit" onclick="Submit()">Submit</button>

You've specified that the button should perform a form submission when clicked, hence the javascript fires, changes the text and the page is reloaded (post back occured).

To get around that, you implement one of the following changes:

  • Change your markup to just be a button that fires javascript:

<input type="button" onclick="Submit()">Submit</input>

  • Add a statement in your javascript that cancels the default action for your submit button:

event.preventDefault(); MDN Link

like image 24
cillierscharl Avatar answered Apr 09 '23 18:04

cillierscharl