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?
Solved: Uncaught Type Error: Cannot Set a Property The toString() is a built-in JavaScript function that converts a number into a string first, and then you can convert that string to upper case characters using the toUpperCase() function.
Answer: Altogether, these are string functions, but the strchr () is an advanced function under the C string header file. Explanation: It has functions to find part in string, whereas; other string parts are utilized for dissimilar functions.
According to the Mozilla website for developer documents, “the TypeError object represents an error when a value is not of the expected type.” Uncaught means that the error was not caught in the catch part of the try-catch block.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With