javascript runtime error 0x800a1391 - javascript

I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal

you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>

Related

Can't figure out how to randomly generate numbers with a button in javascript

followed a tutorial just with different layout and names and still can't seem to find whats wrong?
<!DOCTYPE html>
<html>
<head>
<script>
function myrandom() {
var x = math.floor((math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
</body>
</html>
Reason :
What you are doing wrong is that you are using math instead of Math. JavaScript is case sensitive and Math is defined while math is not.
Corrected :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
<script>
var myrandom = () => {
var x = ~~((Math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</body>
</html>
Also please note that it is better that you write the JS code at the end of the body tag and the script tag is the last one in the body tag.
Note :
Note that I edited the snippet provided by you.
The following edits were made
The script tag was moved at the end of body tag
I changed the function and used arrow syntax instead of normal declaration
Changed Math.floor into bitwise ~~
Resources :
Stack overflow script tag
W3 schools script tag
bit wise operators mozilla
bit wise operators W3 schools
Arrow function mozilla
You have a typo, You need to capitalize the first letter of math -> Math.
<!DOCTYPE html>
<html>
<head>
<script>
function myrandom() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
</body>
</html>

How to load an XML file in JavaScript, get specific info from it, and then display it through alert()?

So, I want to make a program that will be able to get user data(a ton of bug names separated by commas), go through, get data for each one, then display all of that data in a table. I have been through rewriting this like 5 times and still nothing happens. Anyone know what is wrong with this code?
My html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 align="center">Bugs</h1>
<p>In the area below, type in each of the insects you want information
about, seperate them with a comma.</p>
<textarea id="insects"></textarea>
<br>
<button type="button" id="go">Find out!</button>
<br>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
document.getElementById('go').onclick = function() {
var input = document.getElementById('insects').value;
var splitted = input.split(',');
for (i = 0; i<splitted.length; i++) {
var bug1 = splitted[i];
var part1 = // I need to assign it to bug1 without any whitespace
var finish = part1.toLowerCase();
find1(bug1);
}
}
function find1(bug) {
var xmlDocument = $.parseXML("externalfile:drive-77136639a78ffb21e72c7c4dfe7f7bb73604aeb3/root/Bugs/bugs.xml");
var pain = $(xmlDocument).find("value[type='" + bug + "'] pain").text();
alert(pain); <!-- This is to see if it works -->
}
</script>
</body>
Here is my XML code(btw the XML file is called bugs.xml and yes they are in the same exact folder in My Drive/Bugs:
<?xml version="1.0" encoding="UTF-8"?>
<bugs>
<bug type="blisterbeetle">
<name>Blister Beetle</name>
<pain>55</pain>
<conservation></conservation>
<habitat></habitat>
<rarity></rarity>
<class></class>
<order></order>
<family></family>
<species></species>
<dangerous></dangerous>
<external></external>
</bug>
</bugs>

Adding html table to javascript using document.write

Looking for some help here. Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for:
Add code to the writeIt function that writes the opening table tag before iterating thru the heros and villians and then the closing table tag. Then modify the makeListItem to return a string in the form of tr td Hero td td Villan /td /tr.
I tried this but am getting a blank html page when try to view.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {"Super Man":["Lex Luther"],
"Bat Man":["Joker", "Riddler",],
"Spider Man":["Green Goblin",
"Vulture", "Carnage"],
"Thor":["Loki", "Frost Giants"]};
function writeIt('<table>'){
for (hero in superData){
var villains = superData[hero];
for (villainIdx in villains){
var villain = villains[villainIdx];
var listItem = makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
document.write(listItem);
}
}
}
function makeListItem(name, value){
var itemStr = "<li>" + name + ": " + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {
"Super Man": ["Lex Luther"],
"Bat Man": ["Joker", "Riddler", ],
"Spider Man": ["Green Goblin",
"Vulture", "Carnage"
],
"Thor": ["Loki", "Frost Giants"]
};
function writeIt() {
document.write('<table>');
for (hero in superData) {
document.write("<tr><td>" + hero + ": <ul>");
var villains = superData[hero];
for (villainIdx in villains) {
var villain = villains[villainIdx];
var listItem = makeListItem(villain);
document.write(listItem);
}
document.write("</ul></td></tr>");
}
}
function makeListItem(value) {
var itemStr = "<li>" + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
I tried this but am getting a blank html page when try to view.
Because you have syntax problems. Use F12 or the Inspector/Developer mode to find out why.
Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for
True, it's often frowned upon, but JavaScript makes it available for a reason, so let's use it.
The first problem is that you seem to have transposed some code...
For example, you have function writeIt('<table>'). I think you meant document.write('<table>');.
function writeIt(){
document.write('<table>');
Next, you have your final document.write outside of your function call.
document.write('</table>');
This should be inside writeIt(), just after your for loop.
Finally, you have some unquoted stuff in your loop...
makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
Should be (single or double quotes):
makeListItem('<tr><td>Hero</td><td>Villan</td></tr>');
But that's still a bit off for a table. For example, Superman has a 1:1 ratio with his villains and Batman has a 1:2 ratio. You should be adding your rows and tables in a more predictable manner, but the above will at least start to give you output to work from.
Finally, an observation is that your makeListItem needs to use <ul> before it uses <li> so those problems need to be resolved. For now, I recommend you just spit the data out and format it later.

HTML 5 Validation Error

StackOverflow,
I'm a NOOB learning slowly. I got some errors when trying to validate the following code in HTML 5 validator and don't know where the errors are:
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
<function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</head>
<body>
</body>
</html>
Errors: Error: Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.
From line 5, column 2; to line 5, column 34
↩ ↩
Error: End of file seen when expecting text or an end tag.
At line 18, column 7
dy>↩
Error: Unclosed element script.
From line 5, column 2; to line 5, column 34
↩ ↩
Any feedback? Thanks guys and gals.
PreYvin
You are using typographical quotes - change these to regular quotes. (single and double)
Ok, you've got a whole lot of invalid code (HTML and JavaScript) here:
<!DoctypeHTML>
Should be (case doesn't matter):
<!DOCTYPE html>
This:
<script type = “text/javascript”>
contains typographically formatted quotes instead of non-formatted quotes, which is a problem, but you don't even need the type=text/javascript anyway, so you can just write:
<script>
function is not an HTML tag, so this:
<function substitute () {
should be:
function substitute() {
Next, you are using formatted quotes in your JavaScript:
var MyValue = document.getElementID (‘mytextbox’).value;
which should be unformatted, like this:
var MyValue = document.getElementID ('mytextbox').value;
HTML isn't case-sensitive, but JavaScript is, so this:
If (myValue ==0) {
needs to be this:
if (myValue == 0)
More quote problems here:
alert(‘please enter a real value in the box’);
Should be:
alert('please enter a real value in the box');
More case-sensitivity issues here:
Return;
Should be:
return;
More quote and case-sensitivity issues here:
Var myTitle = document.getElementbyID (‘title’)
Should be:
var myTitle = document.getElementbyID ('title');
Lastly, when your script is finished and it's time to return to HTML, you didn't close your script, so this:
}
</head>
Should be:
}
</script>
</head>
You can always validate your HTML at: http://validator.w3.org
And, you can validate your JavaScript at: http://www.jslint.com
You also have invalid JavaScript so this should be valid.
<!doctype html>
<HTML>
<head>
<title> Javascript Programming!</title>
<script>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
if (myValue ==0) {
alert(‘please enter a real value in the box’);
return;
}
var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
you have an extra < in your code. but you need to revisit your javascript as it has many problems the script tag is not closed.
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
Lots of basic syntax errors here.
<!DoctypeHTML> should be <!DOCTYPE html>
the first error you listed, (Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.) is due to a funky double quote character: “ It should be " This probably originated from your text editor. What are you using? I like Sublime, but there are lots of options. The important thing is that you use a text editor designed for coding.
the next two errors are due to your script tag not being closed. Just add </script> at the end of the script.
Like I said, these are just simple syntax errors though. What you really need to learn here is how to look at those error messages and tell what's going on. Notice how the error messages reference a line number and column number? That's to tell you where the problem is. (Sometimes it can be off depending on the error, but worry about that later). Take a look at the line it's complaining about, read the error message, and you should be able to figure out what's wrong.
Close your <script> tag.
Remove < from <function
Use regular quotes instead of typographical
space between Doctype and html ie. <!doctype html>
Lastly, keywords should be all smallcase ie. if, return, var
Updated
<!doctype html>
<html>
<head>
<title> Javascript Programming!</title>
<script type = 'text/javascript'>
function substitute () {
var MyValue = document.getElementID ('mytextbox').value;
if (myValue == 0) {
alert('please enter a real value in the box');
return;
}
var myTitle = document.getElementbyID ('title')
myTitle.innerHTML = myValue;
}
</script>
</head>
<body></body>
</html>

Refresh div with button click using random javascript string element

There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});

Categories

Resources