Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Goal:
Write a JavaScript that reads several lines of text and print a table indicating number of one-letter words, two-letter words, etc.appearing in the text.
This is my code to reads several lines of text and prints a table indicating the number of one-letter words, two-letter words, three-letter words, etc. appearing in the text. For example, the phrase; Whether 'tis nobler in the mind to suffer.
The output will be:
Word length Occurrences
1 0
2 2
3 1
4 2 (including 'tis)
5 0
6 2
7 1
But I do not get any output..So I need help. This is what I currently have:
<!DOCTYPE html>
<html>
<head>
<title>
Assignment 1
</title>
<meta charset = "utf-8">
<b>Assignment1 <br> <br>
Name: Omnia Hassan Elshaer <br> <br>
Current Date: <b>
</head>
<body>
<script type="text/javascript">
// the current date.
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
// function to calculate number of occurrences.
function search()
{
var str = document.getElementById("string").value;
var c = new Array();
c=str.split(" ");
var count = new Array(15);
for(var i=0;i<count.length;i++){
count[i]=0;
}
var wordlenght;
for(var j=0;j<c.length;j++){
wordlenght=c[i].length;
count[wordlenght]++;
}
var content= "<table>"+"<thead><th>Word length</th><th>Occurrences</th></thead><tbody>";
for(var m=0;m<count.length;m++){
content+="<tr><td>"+m+"</td><td>"+count[m]+"</td></tr>";
}
content+="</tbody></table>";
document.getElementById("result").innerHTML = content;
//output(count);
}
/*function output(count){
var content= "<table>"+"<thead><th>Word length</th><th>Occurrences</th></thead><tbody>";
for(var m=0;m<count.length;m++){
content+="<tr><td>"+m+"</td><td>"+count[m]+"</td></tr>";
}
content+="</tbody></table>";
document.getElementById("result").innerHTML = content;
}*/
</script>
<br> <br>
<label><b> Enter the string to determine the number of occurrences :<b>
<input name = "string" type = "text" /> </label> <br> <br>
<input type = "button" value = "Result" text="Result" onclick ="search()"/> <br> <br>
<div id="result"> </div>
</body>
</html>
Try this:
const sentence = "Whether 'tis nobler in the mind to suffer"
// get an array with the length of each word
lengths = sentence.split(" ")
.map(word => word.length)
// get the longest word, e.g. "7"
const max = Math.max(...lengths)
// make a sequence from 0 to the longest word: 0,1,...,7
counts = [...Array(max).keys()].map(n => {
// check how often the number occurs in the 'lengths' array
return lengths.filter(x => x === n + 1).length
})
document.getElementById('results').innerHTML = counts.map((count, i) => {
return `<tr><td>${i+1}</td><td>${count}</td></tr>`
}).join('')
<table id="results"></table>
Related
I have a project where we have a compare the original code and code written by the user. The user can code and then on button click we have to compare the written code with original code.
I have both original and new code in string
originalHtml : <html><body style='color:white;background:purple;'></body></html>
newHtml : <html> <body style="background:purple;color:white;"> </body> . </html>
Here there are 3 things to keep in mind
1) White space (should not show the difference for white space)
2) ' and " (should not compare quotes, both are valid in HTML)
3) Attribute order (should show difference only for missing attribute, ignore attributes order)
Any suggestions or alternative solution will be appreciated.
I have created a code pen for you, this will solve your problem.
https://codepen.io/bearnithi/pen/KEPXrX
const textArea = document.getElementById('code');
const btn = document.getElementById('checkcode');
const result = document.getElementById('result');
let originalHTML = `<html><head>
<title>Hello </title>
</head><body>
<p class="hello"></p>
</body>
</html>`
btn.addEventListener('click', checkCode);
function checkCode() {
let newHTMLCode = textArea.value.replace(/\s/g,"");
let oldHTMLCode = originalHTML.replace(/\s/g,"");
if(newHTMLCode === oldHTMLCode) {
console.log(true);
result.innerHTML = 'TRUE';
} else {
console.log(false);
result.innerHTML = 'FALSE';
}
}
<textarea id="code">
</textarea>
</br>
<button id="checkcode">Check Code</button>
<p id="result"></p>
You can convert all of them to one uniform and compare them.
Example:
remove all space, tab (with one space)
replace all ' to "
sort attribute.
and some rule you defined
Example cheerio to get attribute:
var cheerio = require('cheerio');
var yourString = `<html><body attr2='hi' attr1='hello' style='color:white;background:purple;'></body></html>`;
var $ = cheerio.load(yourString);
var yourAttrs = $('body')[0].attribs;
var sorted = {};
Object.keys(yourAttrs).sort().forEach(function(key) {
sorted[key] = yourAttrs[key];
});
console.log(sorted);
I need help with how to code this program in javascript. The javascript code should load a character from a box and a number (N) from another box. When you press a button, N rows prints each one of those with N characters (same characters that are loaded are printed). Before printing, check that it is only available a character in the box where characters are to be entered.
code in html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="theText"></p>
<p id="theNumber"></p>
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<script type="text/javascript" src="script.js" ></script>
</body>
</html>
Code in Javascript:
function printOut(){
var theText = document.getElementById("theText").innerHTML;
document.getElementById("theText").innerHTML=
document.getElementById("theChar").value;
var theNumber = document.getElementById("theNbr").innerHTML;
document.getElementById("theNumber").innerHTML=
document.getElementById("theNbr").value;
var newText= theText;
var outPut;
for(i = 0; i<theNumber; i++){
newText =newText + theText;
}
newText = newText + "<br>";
for( i = 0; i< theNumber; i++){
outPut = outPut + newText;
}
document.getElementById("theText").innerHTML= outPut;
}
There are several issues in your code, even after the corrections you made after comments were made. Some of the more important:
Don't use innerHTML on an input element. It makes no sense. To get its value, use value.
Don't assign to document.getElementById("theNumber").innerHTML: it will replace any HTML you already had, and thus will remove the theNbr input. Any reference to it will fail with an error from now on.
Initialise your variables before reading from them. outPut is never initialised and so outPut + newText will give undesired results.
Although your can do this with for loops, there is a nice string method in JavaScript with which you can repeat a character or even a longer string: repeat.
Here is how it could work:
function printOut(){
var theNumber = document.getElementById("theNbr").value; // Don't use innerHTML
var theChar = document.getElementById("theChar").value;
var oneLine = theChar.repeat(theNumber) + "<br>";
var output = oneLine.repeat(theNumber);
document.getElementById("theText").innerHTML = output;
}
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<p id="theText"></p>
I would like to know how my code could be displayed on a webpage instead of displayed in alert boxes, how do I do this. I understand that id's ect are needed but I am a little confused of where to start. Any help would be good. Thankyou!
<!DOCTYPE html>
<html>
<script>
//Set of variables
var nameCheck = /^[a-zA-Z\s]+$/;
//eliminates anything not relevant
var numberCheck = /^[0-9\.]+$/;
//eliminates anything not relevant
var totHours = 0;
//adds total gaming hours on one day
var dayHours = 0;
//how many on one such day set in i from 1-7
var averHours = 0;
//stores the average by dividing by the tothours by 7
var mostPerDay = 0;
//calculates day with most gamed
var mostOnDay = 0;
//Most hours on ONE day
var moreDays = " ";
//adds an s to the end of days if more than one
var mpd = 0;
//most per day
var ah = 0;
//average hours
var th = 0;
//total hours
var name = prompt("What is your name?");
//asks users name
//Make sure user inputs a name that includes letters and or spaces
while (name == "null" || isNaN(name) == false || !name.match(nameCheck)){
alert("Invalid Name!");
name = prompt("What is your name?");
}
//Greets the user by name
alert("Hello " + name );
//Ask how many hours gamed on a day
for (var i = 1; i <= 7; i++){
dayHours = prompt("How many hours have you gamed on day " + i + "?")
//Reask the question if the user inputs an invald answer
while (dayHours == null || isNaN(dayHours) || dayHours > 24 || !dayHours.match(numberCheck) || dayHours < 0){
alert("Incorrect! No letters or symbols, and make sure your input is under 24");
dayHours = prompt("How many hours have you gamed on day " + i + "?")
}
//Adds to total hours
totHours += Number(dayHours)
//Calculates days with most hours gamed
if (mostPerDay > dayHours){
}
else if (mostPerDay < dayHours){
mostPerDay = Number(dayHours);
mostOnDay = i;
}
else if (mostPerDay = dayHours){
mostOnDay += " and " + i;
mostPerDay = Number(dayHours);
}
}
//Adds 's' to the statistics if more than one day
if (isNaN(mostOnDay) == true){
moreDays = "s ";
}
//Divides the total hours by 7 to get average over those 7 days
aver = (totHours / 7);
//Calculates and rounds to the value of 1
th = totHours.toFixed(1);
ah = aver.toFixed(2);
mpd = mostPerDay.toFixed(1);
//States calculated statistics
alert("\nTotal gaming hours this week " + th + "\nAverage gaming hours this week " + ah + "\nMost on one day" + moreDays + mostOnDay + " for " + mpd + " hours." );
//Comments on average hours per day gamed
if (averHours <= 2){
alert("Healthy amount of gaming this week")
}
else if (averHours <= 24){
alert("Unhealthy amount of gaming this week")
}
</script>
</html>
There are several ways to include JavaScript in an HTML document:
Put the JavaScript code in a separate filename.js document and refer to it in the header of the HTML document (that is, between <head> and </head>) as follows: <script type="text/javascript" src="filename.js"></script>. This is the "cleanest" option as it separates functionality (JavaScript) from structure (HTML).
Put the JavaScript code directly in the header of the HTML document; that is, between <script type="text/javascript"> and </script> (no src attribute here)
In the body of the HTML document, again between <script> and </script>, for example when you want to dynamically add text with document.write('');
Changing the text in a <div id="mydiv"> can be done by accessing it via its id:
document.getElementById('mydiv').innerText = 'text';
or through the variants innerHTML, outerText or outerHTML.
For easy DOM manipulation, you may want to look into jQuery. Also, keep in mind that the JavaScript code in the header or external file will be executed immediately, which may cause errors if certain parts of the document body aren't loaded yet. jQuery offers an elegant solution by wrapping the code in
$(document).ready(function () {
// code here
});
Good luck!
A simple method to do this would be to include a link to an external javascript file:
<script src="path/myfile.js"></script>
at the bottom of your html file. If your script requires jQuery, make sure it is linked as an external script before your script. You can reference html elements in your javascript file by giving your html tags an id or class. For example:
In HTML:
<div id = "mydiv"> </div>
Select element in JS:
$('#mydiv')
If you are trying to make your web page more reactive, you may want to look into jquery. It's a lightweight javascript library that can help you make your web page more interactive. Check out the tutorial below:
http://www.w3schools.com/jquery/
I don't entirely understand your question, but just in case you are asking if the javascript will literally show up on your web page, it won't unless you display it as text. If you want to debug your javascript code, you can use developer tools on Chrome or something like it on other browsers:
https://developer.chrome.com/devtools
I debugged my code plenty, but I am still having issues. This is a class assignment and I asked my professor and he is stunned as well. I am certain that fixing this error will help me with my code, but what I got wrong I am not sure. Could you help? Here is the error
Here my html code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Magic Word - Sample</title>
<script src="magicWord.js"></script>
</head>
<body>
<div>
<h2 align="center">WELCOME TO MAGIC WORD!</h2>
<h3>Please enter your guess on the space below:</h3>
<div>
<input type="text" id="guestGuess" />
<input type="submit" id="submitButton" onclick="javascript:enteredGuess();" />
</div>
</div>
<div>
<h3>Your guesses so far are: </h3>
<div id="userGuesses"></div>
<div>You have guessed: <span id="userAttempts"></span> times</div>
</div>
</body>
</html>
Here is my Javascript
var numOfAttempts = 5;
var numOfGuesses = 0;
var magicWord = "Just";
function guessesUsed(attemptsTaken) {
var numGuessesLeft = document.getElementById("userAttempts");
numGuessesLeft.innerHTML = attemptsTaken;
}
//function guessesLeft(attemptsLeft) {
// var numGuessesUsed = document.getElementById("guessesLeft");
// numGuessesUsed.innerHTML = attemptsLeft;
//}
function listWordsUsed(wordUsed) {
var userTrials = document.getElementbyId("userGuesses").innerText;
var divisor = document.createElement("div");
divisor.innerHTML = "<div id=" + wordUsed + ">" + wordUsed + "</div>";
userTrials.appendChild(divisor);
return;
}
function enteredGuess()
{
//A user will enter a word and the word will be checked against the magic word
//var enterGuess = prompt("What is your guess?", "Enter your guess here");
var theGuess = document.getElementById("guestGuess");
var magicWordResult;
// Used lower case for both instances to compare both words
if (theGuess.value.toLowerCase() == magicWord.toLowerCase())
{
//The user guesses the correct word
magicWordResult = "Your guess was" + theGuess + "! Nice going!";
//document.writeln("Your guess was: " + guestGuess + "\nand the magic word is " + magicWord);
}
else //The user guesses wrong
{
//When user gets it wrong increase by one the numOfGuesses
numOfGuesses ++;
magicWordResult = "Your guess was" + theGuess + ". Nice try, but that's wrong, try again. \nYou have used " + numOfGuesses + " guesses.";
// Subtract the amount of guesses from the amount of attempts
var guessesLeft = numOfAttempts - numOfGuesses;
if (numOfGuesses == numOfAttempts)
{
// When the user has reached all its attemps
magicWordResult = "Sorry, you ran out of guesses. The magic word was " + magicWord + ".";
}
else
{
magicWordResult = "You still have " + guessesLeft + " guesses left.";
}
//To show the number of guesses the user has used
guessesUsed(numOfGuesses);
//To show the number of guesses the user has left
//guessesLeft(guessesLeft);
//Creates a list of the words used by the user
listWordsUsed(theGuess);
}
// Display in an alert mode and show how the user is doing
alert(magicWordResult);
}
Where is my error?
This:
var userTrials = document.getElementbyId("userGuesses").innerText;
gets the text of the "userGuesses" element as a string, but here:
userTrials.appendChild(divisor);
your code treats it as if it were a DOM node. Because there's no "appendChild" property on a String instance, it's undefined, and that explains the error — you're trying to make a function call but the function reference is undefined instead.
edit — oh also that typo in "getElementById()" is also important, as noted by crclayton in a comment. I missed that one :) The general trick to dealing with the
undefined is not a function
error is to try and find a place where your code might come up with undefined instead of a reference to a function. The primary causes, in my experience, are:
Typos, like the "getElementbyId" thing. If the function name is misspelled, JavaScript won't understand that and so it can't give a better error.
Unsatisfied assumptions about what a variable or property refers to, as in the userTrials variable.
Assumption that some function returns a reference to a function, when it in fact (might) return undefined
I'm making a simple game for selling anchovies. I have an upgrade to buy a small fishing net. The fishing net costs a certain amount of anchovies, so I subtract that number from the total and then rewrite using innerHTML. I want this small net to add 1 anchovy every second, so I use window.setInterval. However, now every second [object HTMLSpanElement] is written to the page.
What do I do?
Here is the jsfiddle link: http://jsfiddle.net/Bj6M5/1/
And here is the code:
<head>
<script type="text/javascript">
var anchovies = 0;
var money = 0;
function goFish(num) {
anchovies = anchovies + num;
money = 0.433 * anchovies;
var money_rounded;
money_rounded = money.toFixed(2);
if (anchovies != 1) {
document.getElementById("anchovies").innerHTML = anchovies + " anchovies";
}
else {
document.getElementById("anchovies").innerHTML = "1 anchovy";
}
document.title = "$" + money_rounded + " - Anchovy Bros.";
}
function buySmallNet(){
var smallnet_price = Math.floor(10 * Math.pow(1.1,smallnets));
if (anchovies >= smallnet_price) {
smallnets = smallnets + 1;
anchovies = anchovies - smallnet_price;
if (smallnets != 1) {
document.getElementById("smallnets").innerHTML = smallnets + " small nets";
}
else {
document.getElementById("smallnets").innerHTML = "1 small net";
}
document.getElementById("anchovies").innerHTML = anchovies + " anchovies";
}
else {
alert("You don't have enough anchovies!");
}
}
window.setInterval(function(){
goFish(smallnets);
}, 1000);
</script>
<title>$0 - Anchovy Bros.</title>
</head>
<body>
<button onclick="goFish(1);">FISH!</button>
<br>
<span id="anchovies"></span>
<div style="float:right;" id="upgrades">
<center>
<button onclick="buySmallNet();">small fishing net</button>
<br>
<span>costs 15 anchovies</span>
<br>
<span id="smallnets"></span>
</center>
</div>
</body>
You're calling goFish(smallnets). smallnets is the id of an element, so you're passing that element. You're expecting a number in goFish and do all kinds of calculations and assignments, which obviously fail, because it's an element and not a number. In the end, you're outputting anchovies, which is now assigned that element, instead of the result of a calculation.
So there's a missing links somewhere where you need to convert the element to a number, which should probably be the contents of the element (being the number of small nets in posession).
The reason is this line:
goFish(smallnets);
You haven't declared a smallnets variable anywhere, but you have an element in your markup with the id "smallnets" which is a span. Most browsers create global variables for elements with id values, where the name of the variable is the id and the value is the DOM element.
Then in goFish, this line:
anchovies = anchovies + num;
is (on the first pass):
anchovies = 0 + a_span_element;
Since the span can't be reasonably converted to a number, it's converted to a string, which is "[object HTMLSpanElement]". Then the 0 is converted to a string and you have "0[object HTMLSpanElement]".
And then the next time the interval fires, you add another copy of "[object HTMLSpanElement]" to it, etc., etc.
If your goal is to use the text of the span, you want:
goFish(smallnets.innerHTML);
or better
goFish(parseInt(smallnets.innerHTML, 10));
or even better, don't rely on the global created via the id:
goFish(parseInt(document.getElementById("smallnets").innerHTML, 10));
You'll also want to put 0 or something in the span, e.g.:
<span id="smallnets">0</span>