Below code does not enumerate the properties & values of Array constructor on a web page.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
window.onload = myfunc;
function myfunc(){
window['Object']['getOwnPropertyNames'] (window['Array'])['forEach'](function(val){
document.write(val + ": " + Array[val] + "<br />" );
});
}
}
</script>
</head>
<body>
</body>
</html>
Is there any issue with the argument passed to forEach?
No the argument is fine, you have an extra } closing bracket.
window.onload = myfunc;
function myfunc(){
var x = "";
window['Object']['getOwnPropertyNames'] (window['Array'])['forEach'](function(val){
x += val + ": " + Array[val] + "<br />" ;
});
document.write(x);
}
I hope that you know document.write will replace the whole document. Moreover i have appended whatever you want to print in a variable x, you can use this x to display the output.
using Object.getOwnPropertyNames(Array); would be better
but if want to insist on you method then :
window['Object']['getOwnPropertyNames'] (window['Array'])['forEach'](function(val){
console.log(val);
});
you had an extra }
You have an extra closing curly brace in your code, which you can see easier when you fix the indentation of your code:
}
</script>
You can use window objects directly, there is no need for window['propertyName'].
window['Object']['getOwnPropertyNames'](...)
// is the same as
Object.getOwnPropertyNames(...)
You may want to use .forEach to call a method on returned results, not ['forEach']:
Object.getOwnPropertyNames(window).forEach(function (propName) {
console.log('In global window scope: ', propName);
});
Related
<html>
<head>
<title>functionTesting</title>
</head>
<body>
<p id = "test" >test</p>
<script type = "text/javascript" >
function change(string){
//return string + ": Modified"
document:getElementById("test").innerHTML = string + ": Modified"
}
change("1234")
</script>
</body>
</html>
the test is never changed to "1234: Modified. It seems to stay as "test" unless I get the element outside the function then change it.
This line:
document:getElementById("test").innerHTML = string + ": Modified";
Should be:
document.getElementById("test").innerHTML = string + ": Modified";
You have a syntax error. Change:
document:getElementById
To:
document.getElementById
(colon to a period)
I have been messing with this code for a bit too long now, so I thought I'd apply for some help...
This just don't work at all for me. Does anyone know what I am doing wrong here?
Any advice appreciated.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bad Math (typeConv)</title>
</head>
<body>
<h1>Doing bad math... will she run??</h1>
<button type="button" onclick="addWrong()">addWrong</button>
<button type="button" onclick="sayHi()">sayHi</button>
<script>
function addWrong() {
var x = prompt("X?");
var y = prompt("Y?");
var sum = x + y;
alert(x " + " y " = " + sum);
} // end addWrong
function sayHi() {
alert("Hi");
}
</script>
</body>
</html>
In your "alert" call inside your "addWrong" function, you aren't doing the string concatenation correctly.
The plus' go around the variables, outside of the string quotes:
alert(x + " + " + y + " = " + sum);
Just a little mix up of the quotes.
You should read up on string interpolation (using variables inside of strings). There are two problems with your code:
alert(x " + " y " = " + sum);
x and y are defined variables, and are being evaluated alongside strings without any sort of operators indicating how you want them to interact. This is the same thing as typing x"r"y"z", which would also error out. You could write it as:
alert(x + " + " + y + " = " + sum);
But that is pretty confusing to read. See below for my suggestion.
The other problem is how you are adding the inputs from prompt("X?") and prompt("Y?").
var x = prompt("X?");
No matter what the user answers, it will be coerced into a string. And when you add two strings together, the '+' operator is used to concatenate the strings, instead of add them together (as integers). So you would need to convert the inputs into an integer. There are better ways to account for edge cases, but the simplest way is to call parseInt() around X and Y:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bad Math (typeConv)</title>
</head>
<body>
<h1>Doing bad math... will she run??</h1>
<button type="button" onclick="addWrong()">addWrong</button>
<button type="button" onclick="sayHi()">sayHi</button>
<script>
function addWrong() {
var x = prompt("X?");
var y = prompt("Y?");
var sum = parseInt(x) + parseInt(y);
alert(`${x} + ${y} = ${sum}`);
} // end addWrong
function sayHi() {
alert("Hi");
}
</script>
</body>
</html>
I am trying to create code that when you press a button, it will change the value of a variable and replace some text.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="unitts">You have 0 unitts</p>
<script type="text/javascript">
var unitt = 0;
function unittIncrease() {
var unittPrev = unitt;
unitt++;
document.getElementById(unitts).innerHTML.replace("You have " + unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");
}
</script>
<button id="unittIncrease" onclick="unittIncrease();">Digitize Unitt</button>
</body>
</html>
When I press the button, nothing happens to the text.
I don't know why this does not work.
Please help me!
EDIT: I am only 11 years old,
please don't throw your wizard
code at me.
maybe you should remove your button system and add a while loop that
automatically add a unit but waits one second with a setInterval
function
I think you should write the js code like this
document.getElementById('unitts').innerHTML = "You have"....
Instead of:
document.getElementById(unitts).innerHTML.replace("...")
Your JavaScript should be (note the unitts wrapped in quotes and the full stop removed):
document.getElementById('unitts').innerHTML = "You have " + unitt + " unitts";
Instead of:
document.getElementById(unitts).innerHTML.replace("You have " + unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");
In the latter, it is looking for the non-existent variable unitts instead of the string 'unitts'. Also, you are looking for the text You have x unitts. which cannot be found because in your HTML, it is just You have x unitts without the full stop.
Edit
See this plnkr.
Apart from the issues that the other answer mentions, by calling .replace method on the .innerHTML property of the element, the content of it doesn't change. You should reset the property by using the returned value of the method call:
el.innerHTML = el.innerHTML.replace(...);
Also, as you are trying to increase a number, instead of replacing all the characters, you can just replace the numeric part:
var unitts = document.getElementById('unitts');
function unittIncrease() {
unitts.textContent = unitts.textContent.replace(/\d+/, function(n) {
return +n + 1;
});
}
https://jsfiddle.net/h6odbosg/
I am trying to create a button that will display browser details in a new document using javascript. I have searched here and w3schools and am quite stumped! I am really new to javascript so any advice is greatly appreciated. Thanks!
<html>
<head>
<script type="text/javascript">
function docOpen()
{
document.open();
document.write(browserDetails);
}
function browserDetails () {
var x = navigator
document.write("CodeName=" + x.appCodeName)
document.write("<br />")
document.write("MinorVersion=" + x.appMinorVersion)
document.write("<br />")
document.write("Name=" + x.appName)
document.write("<br />")
document.write("Version=" + x.appVersion)
document.write("<br />")
document.write("CookieEnabled=" + x.cookieEnabled)
document.write("<br />")
document.write("CPUClass=" + x.cpuClass)
document.write("<br />")
document.write("OnLine=" + x.onLine)
document.write("<br />")
document.write("Platform=" + x.platform)
document.write("<br />")
document.write("UA=" + x.userAgent)
document.write("<br />")
document.write("BrowserLanguage=" + x.browserLanguage)
document.write("<br />")
document.write("SystemLanguage=" + x.systemLanguage)
document.write("<br />")
document.write("UserLanguage=” + x.userLanguage)
}
</script>
</head>
<body>
<form>
<input type="button" onclick="docOpen()" value="Get Browser Details">
</form>
</body>
You have a curly double quote in place of a normal (straight) double quote here:
document.write("UserLanguage=” + x.userLanguage)
^
This is causing a syntax error. Replace it with a straight quote.
The problem is that you aren't invoking either of the functions you've defined. The call to browserDetails isn't a call, it's just a reference, and nothing is invoking the docOpen function.
Change line 4 to document.write(browserDetails());
Then invoke docOpen docOpen()
You'll also need to fix the smart quote as instructed by duskwuff.
I made a working fiddle at: https://jsfiddle.net/87q1a0kn/
You can do something like
<html>
<head>
<script>
function docOpen()
{
document.open();
document.write(browserDetails()); // ADD '()' to call the function
}
function browserDetails () {
var x = navigator;
// iterate through all properties and get the values
for(var prop in x) {
document.write(prop+' = '+ x[prop]+'<br />');
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="docOpen()" value="Get Browser Details">
</form>
</body>
EDIT based on #Barmar comment
<script>
function docOpen()
{
document.open();
browserDetails(); // ADD '()' to call the function --
}
function browserDetails () {
var x = navigator;
// iterate through all properties and get the values
for(var prop in x) {
document.write(prop+' = '+ x[prop]+'<br />');
}
}
</script>
I am having problems when I try to pull it up on my computer the page is blank. I am not understanding this. Like when you click on the file button on the internet and you click open file that file shows up blank. Can someone help me understand why it is doing that. Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Week 10</title>
<script type="text/javascript">
/ *<![CDATA[ */
Var name;
firstName = "Valerie";
lastName ="Shipbaugh";
var placeOfBirth;
name=FirstName +"";
name += lastName;
placeOfBirth ="Houston";
placeOfBirth +=",Texas";
nameArray = name.split("");
/*]]>*/
</script>
</head>
<body>
<script type="text/javascript">
//<![CDATA[
document.write("<p> My first name is : + nameArray[0]
+ "<br />");
document.write("My last name is: "+ nameArray[1]
+ "<br />");
*/
The brackets[] specifies alternate characters allowed in a patch pattern.
It uses metacharacters which are special characters that define the pattern matching rules ina regular experession.
*/
document.write("There are " + firstName.length
+ " characters in my first name" + " <br/>");
*/
This one called the length property.
This returns the number of characters in a string.
*/
document.write("I was born in " + placeOfBirth + " <br/>");
*/
With this string we are using concatenation operations.
*/
document.write("<p>My initials are: " + firstName.charAt(0) +
lastName.charAt(0) + "</p>");
*/
The last one return the character at the specific position in a text string
returns an empty string if the specified position is greater than the length of the string.
*/
//]]>
</script>
</body>
</html>
So where my comments are to explain what is going on is in the wrong place???
There is a more general way to solve this problem:
Take everything out of this file and
copy it into notepad.
Put just the
<html>and </html> into the file
Begin copying very small blocks into
the file one at a time, each time
reload the page
Soon you will see
one small block that causes the
failure, then you can assess that
small block.
Look at errors reported by the browser (tools->error console in firefox for example) it will hi-light errors such as you mismatched /**/ comments & the missing closing quote character from;
document.write("<p> My first name is : + nameArray[0]
Also js is case sensitive so its var not Var, which you should use to define all your variables such as firstname (which you incidentally later refer to as Firstname) etc.
Of course it won't work, the comment blocks aren't even right:
*/
The brackets[] specifies alternate characters allowed in a patch pattern.
It uses metacharacters which are special characters that define the pattern
matching rules ina regular experession.
*/
Should be:
/*
The brackets[] specifies alternate characters allowed in a patch pattern.
It uses metacharacters which are special characters that define the pattern
matching rules ina regular experession.
*/
Also, you really should avoid using document.write. In certain cases, that is what causes a blank page (if I remember correctly, when you use it after page load).
JavaScript is case sensitive - so in the first section of your scripts:
Var name; //var is with a lowecase "v"
firstName = "Valerie";
lastName ="Shipbaugh";
var placeOfBirth;
name=FirstName +""; //firstName was created with a lowecase "f"
Later you have this...
document.write("<p> My first name is : + nameArray[0]
+ "<br />");
You're missing a quote in there, should be
document.write(" My first name is : " + nameArray[0]
+ "");
And finally, comments open and close like this:
/* comment */
Not like this
*/ error */
Fixing these things will make the script run. However, it's not doing what I suspect you want. You are trying to split() the string containing the name, but there's nothing to split it on. You need to add a space between then and try this:
nameArray = name.split(" ");
You can see this working here:
http://jsfiddle.net/CM7fx/
Test in multiple browsers and make sure you have javascript enabled id' suggest first
The comments were wrong, the variable name are case sensitive. Here is a working version without comments, you can re-add those
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Week 10</title>
<script type="text/javascript">
var name;
var firstName = "Valerie";
var lastName ="Shipbaugh";
var placeOfBirth;
name= firstName + " " + lastName;
placeOfBirth ="Houston ,Texas";
var nameArray = name.split(" ");
</script>
</head>
<body>
<script type="text/javascript">
document.write("<p> My first name is : " + nameArray[0] + "<br />");
document.write("My last name is: " + nameArray[1] + "<br />");
document.write("There are " + firstName.length + " characters in my first name" + " <br/>");
document.write("I was born in " + placeOfBirth + " <br/>");
document.write("<p> My initials are: " + firstName.charAt(0) + lastName.charAt(0) + "</p>");
</script>
</body>
</html>