JavaScript onclick why does it say function not defined? - javascript

I have been writing this code to generate a countdown maths question and answer, but it doesn't work when i run it (sorry for questionable variable names also this is one of my first times using JavaScript so i might not be doing sone things right):
function remove(arr, value){
for( var i = 0; i < arr.length; i++){
if ( arr[i] === value) {
arr.splice(i, 1);
}
}
}
function pop(array, value){
let n = array[value]
remove(array, value)
return n;
}
let num = [25, 50, 75, 100]
let anum = []
function genrt(){
let leng = parseInt(document.getElementById("i1");)
let small = parseInt(document.getElementById("i2");)
for(i=0; i<leng; i++){
anum.push(Math.floor(Math.random()*10)+1)
}
for(i=0; i<small; i++){
anum.push(num[Math.floor(Math.random()*3)])
}
document.getElementById("1").innerHTML = "Your numbers are: " + String(anum);
let nuum = Math.floor(Math.random()*(anum.length-1))
let out = anum[nuum]
remove(anum, nuum)
ans = String(out)
lenggg = Math.floor(Math.random()*anum.length-3)+3
for(i=0; i<lenggg; i++){
let op = Math.floor(Math.random()*3)
let nnuu = Math.floor(Math.random()*(anum.length-1))
let nuuuum = anum[nnuu]
remove(anum, nnuu)
if(op==0){
out+=nuuuum
ans+='+'
}
if(op==1){
out-=nuuuum
ans+='-'
}
if(op==2){
out*=nuuuum
ans+='*'
}
if(op==3){
out/=nuuuum
ans+='/'
}
ans+=String(nuuuum)
ans+='\n'
}
document.getElementById("2").innerHTML = "Your target is: " + String(out);
}
function reveal(){
document.getElementById("3").innerHTML = "The solution is (without bodmas): " + ans;
}
<!doctype html>
<html>
<head>
<title>countdown generator</title>
</head>
<body>
<p>How many small numbers</p>
<input type="int" id="i1" value=3>
<p>How many big numbers</p>
<input type="int" id="i2" value=2>
<button onclick="genrt()">Generate</button>
<p id="1">Your numbers are:</p>
<p id="2">Your target is:</p>
<button onclick="reveal()">Solve it</button>
<p id="3">The solution is (without bodmas)</p>
</body>
</html>
But when i press the generate button it says function genrt not defined. I have looked for an answer for ages and tried quite a few things but nothing seems to work, does anyone know what i am doing wrong?

You have syntax errors on these lines:
let leng = parseInt(document.getElementById("i1");)
let small = parseInt(document.getElementById("i2");)
You have misplaced ; symbol. You should always read console output, the error was clearly visible in the console logs.

Your script has a syntax error. The first error you should be seeing in your console is
Uncaught SyntaxError: missing ) after argument list
Obviously, since it failed to compile the Javascript, then when you afterwards try to call a function from that failed block, it will not exist because the JS engine couldn't read the code in order to load it.
If you fix the syntax error then the undefined function error will go away. It's actually a fairly simple couple of typos:
let leng = parseInt(document.getElementById("i1");)
let small = parseInt(document.getElementById("i2");)
needs to become
let leng = parseInt(document.getElementById("i1"));
let small = parseInt(document.getElementById("i2"));
; is always to end a line - if you have something after the ; which doesn't of itself form a valid line of code, then you know it's definitely wrong. I suggest using an IDE or code editor which understands JavaScript syntax and can highlight these kinds of issues to you before you even attempt to run the code.
(I make no guarantees that you won't then have other unrelated errors or bugs, I haven't tested the code to that extent.)

there wqs semicolon in on those lines
let leng = parseInt(document.getElementById("i1");)
let small = parseInt(document.getElementById("i2");)
ans variable was not difine
but i dont know if the result is what you want
i have make some corrections
<html>
<head>
<title>countdown generator</title>
</head>
<body>
<script>
function remove(arr, value){
for( var i = 0; i < arr.length; i++){
if ( arr[i] === value) {
arr.splice(i, 1);
}
}
}
function pop(array, value){
let n = array[value]
remove(array, value)
return n;
}
let num = [25, 50, 75, 100]
let anum = []
let ans = null
function genrt(){
let leng = parseInt(document.getElementById("i1"))
let small = parseInt(document.getElementById("i2"))
for(i=0; i<leng; i++){
anum.push(Math.floor(Math.random()*10)+1)
}
for(i=0; i<small; i++){
anum.push(num[Math.floor(Math.random()*3)])
}
document.getElementById("1").innerHTML = "Your numbers are: " + String(anum);
let nuum = Math.floor(Math.random()*(anum.length-1))
let out = anum[nuum]
remove(anum, nuum)
console.log(String(out))
ans = String(out)
lenggg = Math.floor(Math.random()*anum.length-3)+3
for(i=0; i<lenggg; i++){
let op = Math.floor(Math.random()*3)
let nnuu = Math.floor(Math.random()*(anum.length-1))
let nuuuum = anum[nnuu]
remove(anum, nnuu)
if(op==0){
out+=nuuuum
ans+='+'
}
if(op==1){
out-=nuuuum
ans+='-'
}
if(op==2){
out*=nuuuum
ans+='*'
}
if(op==3){
out/=nuuuum
ans+='/'
}
ans+=String(nuuuum)
ans+='\n'
}
document.getElementById("2").innerHTML = "Your target is: " + String(out);
}
function reveal(){
document.getElementById("3").innerHTML = "The solution is (without bodmas): " + ans;
}
</script>
<p>How many small numbers</p>
<input type="int" id="i1" value=3>
<p>How many big numbers</p>
<input type="int" id="i2" value=2>
<button onclick="genrt()">Generate</button>
<p id="1">Your numbers are:</p>
<p id="2">Your target is:</p>
<button onclick="reveal()">Solve it</button>
<p id="3">The solution is (without bodmas)</p>
</body>
</html>

Related

How do I adjust the code so that the image appears when the website loads and the guess is guessing what I want it to guess?

<!DOCTYPE html>
<html>
<body>
<p id="Image"></p>
Basically what im tryijngto do s
One fix I'd recommend would be splitting your logic into two functions, one the user clicks to check their answer, and one they click to see the next question. This will allow you to display the congrats message on the screen rather than in an alert. Here is that in action:
let score = 0;
let questionsAsked = 0;
const button = document.querySelector('button');
const input = document.getElementById('userInput');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const checkMessage = document.getElementById('check-message');
checkMessage.set = message => checkMessage.innerHTML = message;
checkMessage.clear = message => checkMessage.innerHTML = '';
const options = {
chad: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/600x400/000000/efebe9/?text=John'
}
function askQuestion() {
checkMessage.clear();
input.value = '';
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
document.getElementById('image').innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
button.setAttribute('onclick','checkAnswer()');
button.textContent = 'Check Your Answer!';
}
function checkAnswer() {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
checkMessage.set('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
gameScore.add();
} else {
checkMessage.set('SORRY, IT WAS INCORRECT');
gameScore.subtract();
}
questionsAsked++;
button.setAttribute('onclick','askQuestion()');
button.textContent = 'Next Question';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="checkAnswer()">Start Game!</button>
<input id="userInput" type="text" />
<p id="check-message"></p>
If you would prefer to keep everything in one function and use alerts for the congrats message, you can do so by keeping track of then number of questions asked, and not instantly checking the answer on the first load, like this:
let score = 0;
let questionsAnswered = -1;
const imageContainer = document.getElementById('image');
const button = document.querySelector('button');
const input = document.getElementById('user-input');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const options = {
chad: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/250x250/000000/efebe9/?text=John'
}
function askQuestion() {
questionsAnswered++;
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
if (questionsAnswered) {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
gameScore.add();
alert('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
} else {
gameScore.subtract();
alert('SORRY, IT WAS INCORRECT');
}
questionsAnswered++;
}
imageContainer.innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
input.value = '';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="askQuestion()">Check Answer!</button>
<input id="user-input" type="text" />
Both solutions would work fine with alerts, though the first solution offers some greater flexibility for any functions you make want to perform in between questions. One other main fix there was to make here was to check change the image after checking the answer, and also making sure to actually fun the function in the beginning using askQuestion() in this case. I also added a couple of handy functions gameScore.add() and gameScore.subtract() to ease future use.
You can pass in other integers such as gameScore.add(2) if you every wanted to have double-weighted questions. I also added a Math.max() line to ensure the score never passes below 0. You can remove this if you would like the player's score to pass into negative numbers.
Here is a working version of your game. To begin: <br>
1.Your code was not modifying the src of the image (thus no image appears) <br>
1a. I am modifying the src attribute associated with the `img` tag now. <br>
1b. `document.getElementById("Image").src = randomPhoto;` <br>
2. `theArrayArray` does not exist. I updated the variable to `theArray` <br>
3. To display an image when the game begins you need a handler. <br>
3a. I added the `button` to handle that <br>
4. Unless you want the user to type out `.jpg` you need to remove .jpg <br>
4a. `randomPhoto = randomPhoto.replace(".jpg", "");` <br>
<img id="Image" src="#" width="250" height="250">
<br>
<br>
<input id="userInput" type="text">
<br>
<br>
<button type="button" id="btn" onclick="startGame()">Start Game</button>
<span id="GameScore">Score:</span>
<script>
let score = 10;
var Chad = "Chad.jpg";
let begin = 1;
let thePhoto;
var someArray = [ Chad, Bob
];
function startGame() {
if (start == 0) {
for (var l = 2; i < 3; i--) {
randomPhoto = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = randomPhoto;
document.getElementById("btn").innerHTML = "Submit";
start = 1;
}
} else {
randomPhoto = randomPhoto.replace(".jpg", "Insert");
}
else {
for (var x = 0; i < 3; i++) {
TheName = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = theName;
alert("No");
scorex = score-1;
}
document.getElementById("theScore").innerHTML="Score: "+score;
</script>
</body>
</html>

If statement with OR condition not working

I have no JS or other language background. I have learned everything in the code for this particular problem so bear with me if things aren't clean and clever. I have done a lot of searching before resulting to asking here, so hopefully ALMOST everything is accounted for.
I have a conditional statement I just CANNOT get to run correctly. (entire code for context at the bottom)
if (pyramid < 1 || pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
}
I am most concerned with (pyramid < 1 || pyramid > 8) but if you can help me account for an input value of zero (due to complexities with 0 being false-y), bonus points.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<style id="dennis">
#ahahah {
display: none;
}
</style>
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action="">
<fieldset>
<label>write how tall </label>
<input type="number" id="numberin" min="" max="" step="1" />
<input type="button" value="Make the Pyramid" onclick="makepyramid()" />
</fieldset>
</form>
<script type="text/javascript">
function makepyramid() {
var numberin = document.getElementById("numberin");
var pyramid = numberin.value;
var spaceincrement = numberin.value;
var octoincrement = numberin.value;
var spaces;
var octothorps;
var bringittogether = "";
//WHY YOU NO WORK?! I'd like to make 0 work as well but I am more concerned with the range first.
//first if statement is the ideal, second is bare minimum.
//if (pyramid === null || pyramid < 1 || pyramid > 8) {
//if (pyramid < 1 || pyramid > 8) {
//Put in this if statement to show what SHOULD happen
if (pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
} else {
document.getElementById("ahahah").innerHTML = "";
//decide how many lines to make
for (var a = 0; a < pyramid; a++) {
//number of spaces loop
for (var b = 1, spaces = ""; b < spaceincrement; b++) {
spaces += "_";
}
//number of octothorps in one line loop
for (var c = pyramid, octothorps = ""; c >= octoincrement; c--) {
octothorps += "#";
}
//print spaces, hashes, 2 spaces, start new line
bringittogether += spaces + octothorps + "__" + octothorps + "<br/>";
document.getElementById("giza").innerHTML = bringittogether;
//increment to change next line's number of spaces (one less) and octothorps (one more)
spaceincrement = [spaceincrement - 1];
octoincrement = [octoincrement - 1];
}
}
}
</script>
<hr />
<div id="giza"></div>
<div id="ahahah">
<p><img src="https://i.imgur.com/1A8Zgnh.gif" /> You must select a number between 1 and 8
</p>
</div>
</body>
</html>

Find matched letter from each word in javascript array

I have an array in javascript like that :
var books = ['spring','last night','sweet heart','the sky','tomorrow'] ;
I have textarea
<textarea id="text" name="textpreview" class="text"></textarea>
So what I want is when I enter letter s then I will get two suggestions books just the first word not the second word I mean not sky Just spring and sweet heart .
I will get two spans
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
<span>sweet heart</span>
If I type again after s the p letter like sp in textarea then I will get just spring
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
and so on .
If I type n I will get nothing.
If I type t I will get tomorrow and the sky
Hope it can be done . Thanks for your support .
This help you :
<html>
<head>
<title></title>
</head>
<body>
<textarea id="text" name="textpreview" class="text"></textarea>
<p id="x"></p>
<script>
var x = document.getElementById("x");
var books = ['spring','last night','sweet heart','last night','the sky','tomorrow','tomorrow'];
var txt = document.getElementById("text");
txt.onkeyup = function(event) {
var str = "";
var arr = [];
var index = (txt.value).indexOf("#");
if(index !== -1 && (txt.value).substr(index + 1).length > 0) {
var value = (txt.value).substr(index + 1);
value = value.replace(/[\.\+\*\\\?]/g,'\\$&');
var patt = new RegExp("^" + value);
for(var i=0; i<books.length; i++) {
if(patt.test(books[i]) && arr.indexOf(books[i]) === -1) {
arr.push(books[i]);
}
}
}
if (arr.length < 1 )
x.innerHTML = "";
else {
for(var i=0; i<arr.length; i++)
str+=arr[i]+"<br>";
x.innerHTML = str;
}
}
</script>
</body>
</html>
This problem consists of two parts: Reading and writing your input/output from/to the DOM, and filtering your array books.
The reading and writing part should be easy, there are plenty of guides on how to achieve this.
To filter the books array, JavaScript offers a number of helpful functions:
var books = ['spring','last night','sweet heart','the sky','tomorrow'];
var input = 'S';
var result = books.filter(function(book) {
return book.toLowerCase().indexOf(input.toLowerCase()) === 0;
}).slice(0, 2);
console.log(result); // ['spring', 'sweet heart']
#TimoSta is correct that this is a two-part problem.
I expanded on his code a bit using angular to display the results in the DOM.
http://jsfiddle.net/kcmg9cae/
HTML:
<div ng-controller="MyCtrl">
<textarea id="text" name="textpreview" class="text" ng-model="startsWith"></textarea>
<span ng-repeat="book in sortedBooks()">{{ book }}</span>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.books = ['spring','last night','sweet heart','the sky','tomorrow'];
$scope.sortedBooks = function () {
var sortedBooks = [];
for (var i = 0; i < $scope.books.length; i++){
if ($scope.books[i].toLowerCase().indexOf($scope.startsWith.toLowerCase()) === 0)
sortedBooks.push($scope.books[i]);
}
return sortedBooks;
}
}

How to find if there is a space in a string... tricky

I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}

What's wrong in this simple javascript code?

I want to make a program which can sum up all the digits in a given number. I want my script to return the resul on click of the button Please help me find error in my code. Thanks
<!doctype html>
<html>
<head>
<script type="text/javascript">
function sumdigits()
{
var num=document.getElementById("a").value;
var len=num.length();
alert(len);
if(len!=0)
{
var sum=0;
var ldigit=0;
while(num!=0)
{
ldigit=num%10;
sum+=ldigit;
num/=10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number="+sum;
}
</script>
</head>
<body>
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</body>
</html>
DEMO
onClick should be onclick, length() should be length and sum not out of scope
function sumdigits(){
var num = document.getElementById("a").value;
var len = num.length; // note "length"
var sum; // "sum" scope
alert(len);
if(len!==0){
sum = 0;
var ldigit=0;
while(num!==0){
ldigit=num%10;
sum += ldigit;
num /= 10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number = "+ sum;
}
This is how to make it work, now, I don't know what math you're trying to apply in there and what's it's purpose...
The main reason the script is breaking is because you are calling length() on num variable instead of num.length. Below is a link to a working fiddle with that and a few other adjustments made ( check to see if the value's are integers etc...).
http://jsbin.com/uBAyOJep/1/
<!doctype html>
<html>
<head>
</head>
<body>
<form onsubmit="sumdigits()">
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</form>
</body>
</html>
function sumdigits()
{
var sum = 0,
num = document.getElementById("a").value,
len = num.length,
result = document.getElementById("result");
if( len !== 0 ){
for( var i = 0; i < len; i++){
var lineValue = parseInt(num[i], 0);
if ( !isNaN(lineValue) ) {
sum += lineValue;
}
}
}
result.innerHTML="Sum of digits of the given numbers = " + sum;
}

Categories