user3641959
user3641959

Reputation: 49

.innerhtml is not placing content in "DIV"

I have the following function that should produce a result to a divs named "totalPrice" and "premPrice", however the .innerhtml doesn't seem to be placing the numbers in the div for some reason? Can you perhaps look over this piece of code and tell me possible reasons why it's not inputting the html? Since i am newer to the web languages, do you have to call the function? or when i simply define it is the function called?

html:

            <label class='next action-button'><input type="button"  name="tank" value="Yes" onclick="calculateTotal()" />Yes</label><br/>
 <p>standard and premium system specs</p>
    <br/>
                <div id="totalPrice"></div>
                <br/>
                <div id="premPrice"></div>

js:

function calculateTotal()
{

    var boilerPrice = getBoilerSizePrice() + getBedroomSizePrice() + getBathroomSizePrice()  + getTankSizePrice() ;

    //display the result
    var divobj = document.getElementById('totalPrice');
    divobj.style.display='block';
    divobj.innerHTML = "Your New Boiler Install Price is £"+boilerPrice;

    var divobj = document.getElementById('premPrice');
    divobj.style.display='block';
    divobj.innerHTML = "Premium price £"+((boilerPrice/100)*120);

}

Upvotes: 4

Views: 450

Answers (1)

Kylok
Kylok

Reputation: 769

After writing a function, you need to call it somewhere. After the closing bracket of the function, trying calling it like this:

function calculateTotal()
{

    var boilerPrice = getBoilerSizePrice() + getBedroomSizePrice() + getBathroomSizePrice()  + getTankSizePrice() ;

    //display the result
    var divobj = document.getElementById('totalPrice');
    divobj.style.display='block';
    divobj.innerHTML = "Your New Boiler Install Price is £"+boilerPrice;

    var divobj = document.getElementById('premPrice');
    divobj.style.display='block';
    divobj.innerHTML = "Premium price £"+((boilerPrice/100)*120);

}

calculateTotal();

Edit: Based on your updated intention to call the function on click, I would note that it's considered bad practice to call JavaScript functions inline, and it might give you problems in some cases. Another way to do it is to attach the click event to your target element in your JavaScript code. Here's a jsfiddle using your code.

Basically, I removed the onclick="calculateTotal()" from your button and gave it an ID:

<input id="calc-button" type="button" name="tank" value="Yes" />

Then I added the following line to your JavaScript:

document.getElementById("calc-button").addEventListener("click", calculateTotal);

Upvotes: 4

Related Questions