newQuote not defined unsure why - javascript

Another code to debug for me have to keep it the same as can't rewrite. But Im wondering why newQuote is spitting the error undefined. I also believe that I need to fix the timer setting to get it display as the var tick isn't being called but not 100% sure there any advice is appreciated as I can't find any error beyond the newQuote undefined
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta charset="utf-8" />
<title>Random Proverbs</title>
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function changeQuote() {
quotes = new Array;
quotes[0] = "Laughter is the best medicine.";
quotes[1] = "Never look a gift horse in the mouth.";
quotes[2] = "One good turn deserves another.";
quotes[3] = "The early bird catches the worm.";
quotes[4] = "Two is company, three is a crowd.";
var newQuote = quotes[Math.round(Math.random()+quotes.length)];
document.quoteform.quote.value = newQuote;
}
var tick = setInterval(changeQuote(), 1000); //missing time in milliseconds and double quotes not needed
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
</head>
<body>
<form id="quoteform" action=""> <!--Was -->
<input type="text" size="50" id="quote" name="quote" /><br />
</form>
</body>
</html>

change document.quoteform.quote to document.forms.quoteform.quote
then name the form quoteform
so the new javascript would look like
function changeQuote() {
var quotes = new Array; //was var defintion
quotes[0] = "Laughter is the best medicine.";
quotes[1] = "Never look a gift horse in the mouth.";
quotes[2] = "One good turn deserves another.";
quotes[3] = "The early bird catches the worm.";
quotes[4] = "Two is company, three is a crowd.";
var newQuote = quotes[Math.floor(Math.random()*quotes.length)];
document.forms.quoteform.quote.value = newQuote;
}
setInterval(changeQuote, 1000);
then all you need is change the id to name in the opening form tag

You need to use Math.floor to avoid going outside the bounds of the array, and change the + to * to multiply the random number by the length of the array.
var newQuote = quotes[Math.floor(Math.random()*quotes.length)];

Related

At first it said its not a function, now its just not doing anything

Okay, I'm trying to make a cheesy accent generator to practice with RegEx. But I have a strange problem that seems unrelated to RegEx. The submit button doesn't do anything. At first the function "maccent" was just called "accent" and at that time the console said "accent" was not a function. With nothing better to go on, I assumed it was because the word "accent" was used so many other times, so I changed the function name to "maccent". Now, however, nothing happens. What's the deal? Here is my code:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Accent Generator</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<p>Choose an accent</p>
<input type = "text">
<form action="">
<input type="radio" name="accent" value="German"> German<br>
<input type="radio" name="accent" value="English"> English<br>
<input type="radio" name="accent" value="Indian"> Indian
</form>
<button type="submit" onclick = "maccent()">Submit</button>
<div id = "accented"></div>
<script>
var accent = $('input[name="accent"]:checked').val();
function maccent()
{
if (accent == "German")
{
germAcc();
}
}
function germAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[w]/gi, "v")
//not if it's at the end of a word
var desire2 = desire.replace(/th/, "z")
//replace h too, but not with another z.
//wait, what? It replaces t even if its not followed by h
var desire3 = desire2.replace(/er/, "a")
//this is going to be a hard one
//er is replaced with a but only if its followed by a space or a punctuation
mark.
console.log(desire3);
}
function indAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[r]/gi, "d")
//not if it's at the end of a word
//this words, but not on each indivual word
console.log(desire);
}
function itAcc()
{
}
function britAcc()
{
var sample = $("input").val();
var desire = sample.replace(/[a]/gi, "au")
var desire2 = desire.replace(/er/, "a")
//this is going to be a hard one
console.log(desire2);
//not if it's at the end of a word
}
</script>
</body>
</html>
The problem is the assignment of the "variable" accent. You are doing it at global scope (the top level), so it gets assigned when the page is first loaded.
If you move that assignment into the function maccent() (and move the work "mark" back into the comment it belongs to), your page will work.
Incidentally, the old problem was that you had a function and a variable trying to share the name accent. The variable was "winning".

TypeError: document.quoteform is not defined

I have this pesky problem with my code that I think is a runtime error because it shows up when I run the program and actually stops it. I used an error console to show me where the error is, but I can't make sense of it. If anybody can point me in the right directions without giving me the answer I'd appreciate it. Here is the code:
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function changeQuote() {
quotes = new Array;
quotes[0] = "Laughter is the best medicine.";
quotes[1] = "Never look a gift horse in the mouth.";
quotes[2] = "One good turn deserves another.";
quotes[3] = "The early bird catches the worm.";
quotes[4] = "Two is company, three is a crowd.";
var newQuote = quotes[Math.round(Math.random()+quotes.length)];
document.quoteform.quote.value = newQuote;
}
var tick = setInterval("changeQuote()");
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
</head>
<body>
<form action=""name="">
<input type="text" size="50" name="quote" /><br />
</form>
</body>
</html>
I also have two image of the error console message:

Better way to apply javascript scripts

Hello SO I'm relatively new to html and javascript and I currently want to make a page that will fulfill certain operations such as finding the max number of an array of numbers and factorial of a number as shown below.
and here is how I am organizing these sections
<!DOCTYPE html>
<html lang = "en">
<head>
<title>HTML/CSS Responsive Theme</title>
<meta charset = "utf-8">
<link rel = "stylesheet" href = "main.css" type = "text/css">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<script>
function startFactorial(number)
{
function factorial(num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
document.factorials.factorialsfield.value = factorial(number);
}
function startMaxofFive(str)
{
//can actually find the max of n numbers not limited to 5
function maxoffive(string)
{
var nums = (string.match(/[-]?\d+/g));
var b = nums.map(Number);
return Math.max.apply(Math,b);
}
document.mof.moffield.value = (maxoffive(str));
}
</script>
</head>
<body>
<section id = "first">
<h3>Factorial</h3>
<form name= "factorials">
Enter a number <input type = "number" name = "factorialsfield" value = 0>
<br><br>
<input type = "button" onClick = "startFactorial(factorialsfield.value)" value = "Calculate"/>
</form>
</section>
<br>
<section id = "second">
<h3>Max of Five Numbers</h3>
<form name = "mof">
Enter 5 numbers <input type = "text" name = "moffield" placeholder = " separate each number by commas" size = 26>
<br><br>
<input type = "button" onClick = startMaxofFive(moffield.value) value = "Calculate"/>
</form>
</section>
<br>
<section id = "third">
<h3>Sum and Multiply</h3>
<form name = "operations">
Enter numbers to apply operations <input type = "text" name = "operationsfield"
</form>
</section>
</body>
</html>
What I wanted to ask you all is is there a better way to access those functions in my script without having to create another function just to use them?
Here's some suggestions:
You can use document.getElementById( id ) to get specific elements where id is the HTML's element id <element id="id_name">.
Events allow you to trigger actions based on user input. It works basically the same, but you no longer need to name the functions: element_variable.event = function() { /* ... */ }
See if the inner functions are really neccessary; see if you can edit the code where you no longer need that function (document.getElementById will probably be able to let you do that stuff)
Example:
<form id="factorials" name="factorials">
<!-- Skipping input -->
<input type="submit" <!-- ... -> />
</form>
// Javascript file
var fact = document.getElementById( "factorials" );
fact.onsubmit = function() {
/* Your code here */
}
It's generally considered best practice to move scripts to the bottom of the page before the closing body tag. This way the loading of the scripts won't interfere with page load.
You can also move your scripts to a separate file and include it:
<script src="myscripts.js"></script>
This will help keep your code more neat and organized.
You always use functions to call functions. Sounds weird but thats how it is :P
You can remove the JS calls from your DOM by adding eventlisteners to your JavaScript file just like this example:
<script>
var x = document.getElementById('test');
x.addEventListener('click', function(){
// your function magic happens here
});
</script>
<div id="test"></div>
Sorry if I understood your question wrong
I am not sure that this is what you asked for, however, it seemed like you wanted to know about other methods to get access to your javascript code or script in your HTML.
I can truly recommend you, to look into Angular for this. With Angular you can call methods in your controller, and scope data between your view (HTML) and controller (Javascript).
https://angularjs.org/
But this is just one of many options!

How to get substring using Dojo and javascript

Good Day,
I am a newbie learning Javascript & Dojo and I typically learn by picking apart other parts of running code.
I am confused as to how to get a substring value from the following code (from the ArcGIS Sandbox):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7, IE=9, IE=10">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Query State Info without Map</title>
<script src="http://js.arcgis.com/3.6/"></script>
<script>
dojo.require("esri.tasks.query");
dojo.require("esri.map");
var queryTask, query;
require([
"esri/tasks/query", "esri/tasks/QueryTask",
"dojo/dom", "dojo/on", "dojo/domReady!"
], function(
Query, QueryTask,
dom, on
){
queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");
query = new Query();
query.returnGeometry = false;
query.outFields = ["SQMI","STATE_NAME","STATE_FIPS","SUB_REGION","STATE_ABBR","POP2000","POP2007","POP00_SQMI","POP07_SQMI","HOUSEHOLDS","MALES","FEMALES","WHITE","BLACK","AMERI_ES","ASIAN","OTHER","HISPANIC","AGE_UNDER5","AGE_5_17","AGE_18_21","AGE_22_29","AGE_30_39","AGE_40_49","AGE_50_64","AGE_65_UP"];
on(dom.byId("execute"), "click", execute);
function execute(stateName) {
query.text = dom.byId("stateName").value;
//execute query
queryTask.execute(query, showResults);
}
function showResults(results) {
var s = "";
for (var i=0, il=results.features.length; i<il; i++) {
var featureAttributes = results.features[i].attributes;
for (att in featureAttributes) {
s = s + "<b>" + att + ":</b> " + featureAttributes[att] + "<br>";
}
s = s + "<br>";
}
dom.byId("info").innerHTML = s;
}
});
</script>
</head>
<body>
US state name :
<input type="text" id="stateName" value="California">
<input id="execute" type="button" value="Get Details">
<br />
<br />
<div id="info" style="padding:5px; margin:5px; background-color:#eee;">
</div>
</body>
</html>
All I would like to do is pick apart the input (in this case the id="stateName" which is the word California).
So a silly example would be substituting the following code to get the first 10 characters of when someone types in 'California is on the west coast'
query.text = dom.byId("stateName").substring(0,10);
This is really so I can support other queries but I figured if I can do a substring on this input then it is really the same anytime when I query other attributes.
Thanks in advance for a newbie !
You need to get the innerHTML of your DOM element
query.text = dom.byId("stateName").value.substring(0, 10);
As Thomas Upton correctly pointed out the correct form would be:
dom.byId("stateName").value.substring(0, 10);
apparently the following also works
dom.byId("stateName").value.substr(0, 10);
As noted in comments, a call to .value will deliver what you need. Substring is a method on the string prototype See here. However, dom.byId returns a domNode. You don't want the substring of the domNode itself, you want the substring of the text value of the domNode. On inputs this is easily done with .value and is commonly done with .textContent and .innerHTML as well.

if, if else statement producin error message

I understand that each if statement and each if else statement is contained inside curly braces. That's what I've done here so far. I just started this code and I tested it with only 20% done so that I can fix errors before the code get's too long. With everything looking correct I'm getting a syntax error that for the life of me I can't see where it is. Any suggestions? Here is the code. And here is the link: stickFigure
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>The mysterious road</title>
</head>
<script type="text/javascript">
var curScene = 0
function changedScene(decision){
var message = "";
if(curScene==0) {
curScene=1;
message = "Let the games began!";
}
else if(curScene ==1){
if(decision==1){
curScene = 2;
message = "Looks like you're on the right road.";
}
else(curScene = 3);
message = "you're stading on a bridge overlooking a peaceful stream.";
}
document.getElementById("sceneimg"). src = "scene" + curScene + .png; //There's a syntax error here that I don't see!
alert(message);
}
</script>
<body>
<div style="margin-top:100px; text-align:center">
<p><img id="sceneimg" src="../sfa/scene0.png" alt="Stick Figure" /></p>
Enter here for a glorious adventure!
<input type="button" id="decision" value="1" onclick="curScene(1)" />
Enter this gate for the surpirse of your life!
<input type="button" id="decision" value="2" oonclick="curScene(2)" />
</div>
</body>
</html>
Look here
else(curScene = 3);
and you should be able to work it out.
for the first syntax error you are aware of add say double quoats around the ".png"
and you havent got got ant objects that support the method (no functions found) calling curScene(1) and your only function is changedScene() plus a typo with the oonclick.
and what fearofawhackplanet said.
stick with it, dont give up
Also, even though JavaScript allows it, you're missing a semicolon after your first script statement:
var curScene = 0
Be aware of such omissions. Even though it's not a syntax or semantics error here, this could get you into trouble elsewhere, such as (made up):
return // return undefined
val1 + val2;
Because you use semicolons every where else to terminate your statements, it's best to be consistent.

Categories

Resources