How do I add something to my html using javascript without erasing the whole page

I have a small calculator that I'm adding to my html. It has a few dropdowns to select stuff and when a person hits a submit button, I'd like to display a picture below the calculator in my html. I've tried using a javascript function with: document.write() but that clears the whole page. Is there a way that I can get a javascript function to run which only adds a picture to my page when a submit button is clicked?

Here's a BASIC outline of my code with the part I'm having trouble with:


<script type="text/javascript">

function calc_rate() {

    //code that displays a message after the submit button is hit        




    <td class=rate_calc_label>Select Your Option Type:</td>
<td><select name="type1">

<td class=rate_calc_label>Select The Second Number:</td>
<td><select name="type2">

<td><input type="submit" value="Submit" name="calc_button" onclick="calc_rate()"/></td>



would it be possible to use some kind of inner-HTML? That's what I got from others on stockoverflow but I'm still a little confused



You need a placeholder element for your output. Then set the innerHTML for that element:

<div id='answer'></div>


document.getElementById('answer').innerHTML = "answer is:" + yourdata

Don't use document.write, period. Use DOM operations:


Instead of document.write() you can set the innerHTML property of any DOM node to add text to the page.

Say you add a <div id='result'></div> to the end of the page (before the body tag). Then in your javascript have:

var result_display = document.getElementById('result');
// and in calc_rate():
result_display.innerHTML = "answer";

Note that this will always reset the result_display's text. You can also wrap that operation in a function:

function displayResult(result){
    result_display.innerHTML = '<h2>' + result + '</h2>'; // or whatever formatting


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.