The following loop works:
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
But the following doesn't:
<html>
<body>
<script type="text/javascript">
var i=0;
var x="i=0;i<=5;i++"
for (x)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
I'd just like to create a simple variable.
Please bear with me as I'm a newbie in JavaScript and let me know what I'm missing.
Let me provide my sample Google gadget:
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Sample Gadget" />
<UserPref name="order"
display_name="Results Order"
default_value="i = 0; i <= 5; i++" datatype="enum">
<EnumValue value="i = 0; i <= 5; i++" display_value="Ascending"/>
<EnumValue value="i = 5; i >= 0; i--" display_value="Descending"/>
</UserPref>
<Content type="html"><![CDATA[
<script type="text/javascript">
var i=0;
for (__UP_order__)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
]]></Content>
</Module>
It doesn't work because of the tags <> (they're not supported), and that's why I tried to define a variable for the EnumValue value.
When you say var x="i=0;i<=5;i++" you are creating a text string. This is not interpreted by JavaScript as you are expecting.
There is a definite difference between statements and text strings. Even though it looks to the eye like the same thing, it looks to the interpreter like a text string, like "hello" or "sdflkjsdflkjsdflj". JavaScript is not expecting a text string as loop parameters, it is expecting the three loop control parameters/statements. If you want to have a loop which starts and ends at different points, do something like this...
var i=0;
var start=0; //you can change the start position by changing this
var end=5; //and you can change the end also
for (i=start;i<=end;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
In short: You're confusing code with data. "i=0;i<=5;i++" is data (a piece of text, a string). But when writing a for-loop you have to write initialization, condition and step as code - you cannot pass text that happens to look like the code you'd write there. (In fact, you don't want to - what should happen when the data isn't like valid code? Not to mention it's not needed - see El Ronnoco's)
Because x is a string and you cannot use for statement with a string inside.
If you need to change the upper bound of a for statement you can use a variable instead the fix number 5.
Related
I can't seem to figure out how to do the object part, I need to make it calculate the age dynamically. I've written most of the stuff here and it works fine the only down side is my dynamic age calculation, I don't know what I'm doing wrong and can't find my mistake.
<html>
<head>
<title>WEB PROGRAMIRANJE</title>
</head>
<body>
<script type="text/javascript">
var niza=new Array (9,8,7,6,5,4,3,2,1);
var izbrisani=niza.shift();
var izbrisanip=niza.pop();
var sortirani=niza.sort();
// form an arrey delete first and last:
// sort the arrey:
document.write(sortirani);
function babati(a,b,c)
{
var total;
total=(a+b+c)/3;
alert(total);
}
document.write("<br>");
</script>
<input type="button" value="Call" onClick="babati(0,5,10)";>
<script type="text/javascript">
document.write("<br>");
var ucenik=new Object();
// giving them value to object elements:
ucenik.ime="Name";
ucenik.prezime="Surname";
ucenik.godina=2021;
ucenik.roden=2003;
// printing the object elements:
document.write(ucenik.ime);
document.write("<br>");
document.write(ucenik.prezime);
document.write("<br>");
document.write(ucenik.roden);
document.write("<br>");
// The function:
// This will calculate the age dinamicly This year - Birth year:
ucenik.vozrast=function()
{
this.godina - this.roden;
}
ucenik.vozrast();
document.write(ucenik.vozrast);
//This line above prints the dynamic age:
</script>
</body>
</html>
2 things.
Firstly, the function isn't returning any value so running it won't result in any output.
Secondly, in the document.write(ucenik.vozrast) it writes the function definition rather than running the function and writing the output.
Below is the fixed code.
ucenik.vozrast=function()
{
return this.godina - this.roden;
}
document.write(ucenik.vozrast());
first step you need to return your function expression. Something like this:
ucenik.vozrast= function() {
return this.godina - this.roden;
}
and when you want to paint that result in the DOM you can do something like this
let actualYears = ucenik.vozrast()
document.write(actualYears);
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();
});
I am new to programing and I am trying to learn how to do JavaScript. The problem in my book says I have to write a program using loops in my html page but they are all on the same line.
This is the program:
<html>
<body>
<script>
var sheepCounted = 0;
while (sheepCounted < 10) {
document.write("I have counted " + sheepCounted + " sheep!");
sheepCounted++;
}
</script>
</body>
</html>
but all it returns is:
I have counted 0 sheep!I have counted 1 sheep!I have counted 2 sheep!I have counted 3 sheep!I have counted 4 sheep!I have counted 5 sheep!I have counted 6 sheep!I have counted 7 sheep!I have counted 8 sheep!I have counted 9 sheep!
(all on one line)
I'm also having the problem on this code
My First proper HTML page
<body>
<h1>Hello</h1>
<p>My First web page.</p>
<script>
var name = "Nick ";
document.write("Hello, " + name);
if (name.length > 7) {
document.write("Wow, you have a REALLY long name!");
}
else {
document.write("Your name isnt very long")
}
</script>
</body>
</html>
please HELP ME!!!!!
First of all, using document.write is not recommended. You should do DOM manipulation. However, since you are new to programming, let's not do that.
All whitespace, that is tabs, newlines and spaces, in HTML is truncated to a single space. In order to actually get a line break on the page, use the tag <br />. Alternatively, you can make each text a paragraph, which semantically makes more sense. To do that, just wrap the text in the <p> tag like <p>text</p>
document.write("<p>I have counted " + sheepCounted + " sheep!</p>");
This also applies to your second problem. Just wrap the text in <p>text</p>
If you want to use DOM manipulation, do something like the below code. Please note that this is a bit more advanced, and it's OK to use document.write while taking your baby steps
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8" />
</head>
<body>
<script>
document.addEventListener("DOMContentLoaded", function() {
for (var i = 0; i < 10; i++) {
var p = document.createElement("p");
p.textContent = "I have counted " + i + " sheep!";
document.body.appendChild(p);
}
});
</script>
</body>
</html>
You almost had it. You just need to add a <br /> element after "sheep!" to force a line break:
....
<script>
var sheepCounted = 0;
while (sheepCounted < 10) {
document.write("I have counted " + sheepCounted + " sheep! <br />");
sheepCounted++;
}
</script>
...
I created a javascript program that prints element from my array one by one when you click on the title "click here" , my problem here is that tried to implement a function that deletes a random word from the html page when you click on the words printed previously but it printing other words instead, how can i create a function that removes words printed previously ?
<!DOCTYPE html>
<html>
<head>
<title>function JavaScript</title>
<script >
var k = 0;
var ph = ["red ","blue","black","green","yellow"];
function text(){
if(k < ph.length ){
document.getElementById("test").innerText+=" "+ ph[k];
k++;
}
}
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
</script>
</head>
<body>
<h1 onclick="text();">Click here</h1>
<span id="test" onclick="deleteWord();"></span>
</body>
</html>
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
Your problem is that the += operator appends " "+ ph[number] after the current value of the string.
To replace instead, use the = operator to assign a new value. since you want to delete, just use an empty string.
document.getElementById("test").innerText = "";
As a side note it is unusual to store multiple spaces in your string. If you are trying to move the contents around, you should probably consider setting the padding-left CSS property instead.
edit: if you don't want to lose the entire contents of the element, you can replace the last part of the string:
document.getElementById("test").innerText.replace(/ .*$/,"");
I need to pass arguments to a Excel VBA code from JavaScript of HTA.
I can successfully call VBA function, but unable to pass string arguments correctly.
JavaScript function can pass different string arguments.
Below is code in simple and demo form.
Excel-VBA code
Sub subTest(strName As String)
MsgBox strName
End Sub
HTA code with Javascript
<!DOCTYPE html>
<html>
<head>
<title>HTA</title>
<hta:application
id="oHta"
applicationname="htaNavi"
border="1"
borderstyle = normal
contextmenu = "yes"
caption="Navigator"
sysmenu="yes"
WINDOWSTATE="maximize"
>
</head>
<body>
<input type="button" value="testing" onclick="funRun('testng string')" />
<input type="button" value="testing second" onclick="funRun('testng')" />
</body>
<script>
var objExl;
var objWb;
var objExl =new ActiveXObject("Excel.Application");
objExl.Visible = true;
var objWb = objExl.Workbooks;
var strpath = '\path\testing_excel_web.xls';
objWb.Open(strpath);
function funRun(strName)
{
alert(strName);
objWb.Application.Run('testing_excel_web.xls!subTest(strName)');
}
</script>
</html>
I can call subTest, but message box populates strName as string but not 'testing string' as text.
I'm thinking you want:
objWb.Application.Run('testing_excel_web.xls!subTest("' + strName + '")');
This way, the value of the variable strName is concatenated to the command you are attempting to run.
I know nothing about this calling of a VBA function, so I'm not sure if you need the " around the strName like I provided or not.
In addition, to be safe, in case your strName value contains ", you should use this:
objWb.Application.Run('testing_excel_web.xls!subTest("' + strName.replace(/"/g, "\"") + '")');
Hopefully with this, the value of strName could be
The word "testing" here
or
"Here's a quote"
and it will still work.
The point is that if the string contains ", the Javascript would/could fail. If it would absolutely never contain ", then forget about it. But I think it's needed since any " in the value of strName will break the passing of it as a parameter.