7
votes

I am new to JavaScript and as part of my project for college I need to include some. I created a simple .js file and linked it to my index.html file using <script src="main.js"></script>

I created another page called sellYourHome.html and added a <section> tag with a table and created a simple form that calculates a comission and displays the results back in the input field.

function comCalc()
{
 prcHouse = parseFloat(document.getElementById('prcHouse').value);
 commision =  0.25; 
 result = prcHouse * commision;
 document.getElementById('prcHouse').value = result.toString();
}

That worked.

Now under that function, I wanted to create another one that picks up a <div> element and changes the background-color to, say, blue.

So I created a form on index.html and linked the same .js file to it in the same way.

This is my HTML:

<div id="mainContent">
    <p>hello</p>
    <form id="bgColor">
        <table>
            <tr>
                <td>
                    <input type="button" value="blue" onclick="bgColor('blue');">
                </td>
            </tr>
        </table>
    </form><!-- end of bgColor Form-->
</div>

My javascript is like so:

function comCalc()
{
    prcHouse = parseFloat(document.getElementById('prcHouse').value);
    commision =  0.25;  
    result = prcHouse * commision;
    document.getElementById('prcHouse').value = result.toString();
}

function bgColor(color)
{
  var div = document.getElementById('mainContent');
  div.style.background=color;  
}

When I run this, I get this error on the console:

Uncaught TypeError: String is not a function

I am running this in a browser called SWRIron (which is based on Chrome and is HTML5-complient).

What am I doing wrong?

2
I don't see sting anywhereBrian
My appolgies Typo sting in both instances = "String"StudentwebCoding

2 Answers

5
votes

It's because of your function name bgColor, because bgcolor is an attribute of HTML element and it's clashing with your function bgcolor, browser treats this as an attribute (string) but you used it as a function, so it says string is not a function. So, change the function name to anything else like this

function setBgColor(color)
{
    var div = document.getElementById('mainContent');
    div.style.background = color;
}

Use it as

<input type="button" value="blue" onclick="setBgColor('blue');" />

Example.

0
votes

Yes. Since bgColor is system reserved for HMTL, it throws an error called "Uncaught TypeError: String is not a function". if you change the method name, it will work fine and works fine.