Function returning value 'NaN' - javascript

I am writing a code that checks the user input and gives the result according to it. But the twist here is that the string can also contain the word 'dozen', which just means twelve. The thing will be cleared after looking at the following code:
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>iRock</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<form>
<label for="numDonut">Enter how many donuts you want: </label>
<input type="text" id="numDonut">
<div id="totalDonuts"></div>
<div id="submit" onclick="callDonut();">SUBMIT</div>
</form>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
JS:
//Get string number of donuts entered
var numDonutString = document.getElementById('numDonut').value;
function getTotalDonuts(donutString){
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if(donutString.indexOf('dozen') != -1)
finalDonuts = initialDonutCount * 12;
else
finalDonuts = initialDonutCount;
return finalDonuts;
}
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}
Now here is the problem : No matter what input I give, even if it doesn't contain the word 'dozen', the function returns NaN, which is not making sense.
What can be the problem?

You need to change the function callDonut like :
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}
The problem: you don't reassign the new value of your input into the variable numDonutString

The problem you are having is you have tried to pre define your var numDonutString = document.getElementById('numDonut').value; however what this does is takes a copy of the value and it will never update that value.
So what you need to do is get the new value each time you click the SUBMIT button.
jsFiddle : https://jsfiddle.net/CanvasCode/xue6sbz2/
function getTotalDonuts(donutString){
alert(donutString);
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if(donutString.indexOf('dozen') != -1)
finalDonuts = initialDonutCount * 12;
else
finalDonuts = initialDonutCount;
return finalDonuts;
}
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}

The problem is in the callDonut function and the text box value you are getting is only at the document load, so the value is always NaN.
window.getTotalDonuts = function(donutString) {
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if (donutString.indexOf('dozen') != -1) {
finalDonuts = initialDonutCount * 12;
} else {
finalDonuts = initialDonutCount;
}
return finalDonuts || 0;
}
window.callDonut = function() {
//Get string number of donuts entered
var numDonutString = document.getElementById('numDonut').value;
document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}
<form>
<label for="numDonut">Enter how many donuts you want:</label>
<input type="text" id="numDonut">
<div id="totalDonuts"></div>
<div id="submit" onclick="callDonut();">SUBMIT</div>
</form>
</body>
[DEMO][1]

Related

.toLowerCase() not working among other things not working

JS
var score = 0
var yes = "yes"
var pokemonName = [];
var bg = [];
var index = 0;
document.getElementById('repete').style.visibility = 'hidden';
(function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
})();
function loop() {
var myAnswer = document.getElementById("myAnswer");
var answer = myAnswer.value;
if (answer.toLowerCase().trim() == pokemonName[num].toLowerCase().trim()) {
document.getElementById("text").innerHTML = "Correct, do you want to try again?";
score++
document.getElementById('repete').style.visibility = 'visible';
} else {
document.getElementById("text").innerHTML = "Incorrect, do you want to try again?" + "\n" + " The pokemon was " + pokemonName[num];
document.getElementById('repete').style.visibility = 'visible';
}
}
function loopRepete() {
var repete1 = document.getElementById("repete");
var replay = repete1.value;
if (replay.toLowerCase().trim() == yes.toLowerCase().trim()) {
asyncLoop();
} else {
document.getElementById("text").innerHTML = "Goodbye, your score is " + score;
location.href = 'index.html'
}
}
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pokemon Quiz</title>
</head>
<body>
<lable> Answer </lable>
<input id="myAnswer" type="text">
<button onclick="loop()">click</button>
<p id="text"></p>
<div id="repete">
<lable> Answer </lable>
<input id="loop" type="text">
<button onclick="loopRepete()">click</button>
<p id="loopText"></p>
</div>
<script src="Gen3.js">
</script>
</body>
</html>
When I try take the input from the second second button (div id = repete) and put a toLowerCase() on it it does not work, and we I remove the toLowerCase() it still doesn't work but doesn't show a console error on the page. So I am confused On what I need to try do. I have tried to google it, but I could not find anything that helped.
You have to check if num exists in pokemonName array.
Otherwise, you'll be doing something like this:
[1,2,3][5].toLowerCase() which results in undefined.toLowerCase(), and you can't call .toLowerCase() on undefined as it only exists for String.
If you want asyncLoop to be defined you can't wrap it in a IIFE like that. I suspect you did that so it would run when the page loads, however there's another way to do that and still have the function defined for later use:
// define it like a normal function
function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
}
// and call it right away
asyncLoop();

How can I get value from user for click function using if statement for a password generator?

I'm very new to JavaScript so forgive me if the code is wrong. I have a problem getting a value from the user when the value is a number or letter.
If it is a number the function should execute, but if it is not a number it should display an alert telling the user to input a valid number.
Well, my application displays the alert when the user entry is both a letter and/or a number. Any help would be greatly appreciated.
I have tried using an if statement which will be shown in the code below under the Generate click function.
Edited to include HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Password Generator</title>
<link rel="stylesheet" href="password.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="password.js"></script>
</head>
<body>
<main>
<h1>Password Generator</h1>
<h2>Generate a strong password</h2>
<label for="num">Number of characters:</label>
<input type="text" id="num"><br>
<label for="password">Password:</label>
<input type="text" id="password" disabled><br>
<label> </label>
<input type="button" id="generate" value="Get Password">
<input type="button" id="clear" value="Clear"><br>
</main>
</body>
</html>
"use strict";
$(document).ready(function() {
var getRandomNumber = function(max) {
for (var x = 0; x < length; x++) {
var random;
if (!isNaN(max)) {
random = Math.random(); //value >= 0.0 and < 1.0
random = Math.floor(random * max); //value is an integer between 0 and max - 1
random = random + 1; //value is an integer between 1 and max
}
}
return random;
};
$("#generate").click(function() {
$("#password").val(""); // clear previous entry
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-+!#";
var num;
if (num >= 0 && num <= 100) {
//If the user entry is valid, the function will execute and return password
return num;
//If user entry isn't a valid number, display alert
} else if (isNaN(num)) {
alert(" Please enter a valid number ");
}
}); // end click()
$("#clear").click(function() {
$("#num").val("");
$("#password").val("");
$("#num").focus();
}); // end click()
// set focus on initial load
$("#num").focus();
}); // end ready()
Please provide html part.
and when you click #generate, you didn't define the value of num variable.
Change this line and try again
var num= $("#num").val();
You should get the user input to a variable and validate that
var num = $("#password").val(""); // clear previous entry
if (isNaN(num)) {
return alert(" Please enter a valid number ");
}
else {
if (num >= 0 && num <= 100) {
return num;
else
// ..... return another error message here
}

How to compare the current variable with current type?

In my code I try to comapare the current element from the array tmp with the types string and number. With this compare I want to print in the console the result different, i.e. if is a string to print it on the same line(the whole word), the next word to be on the second line and so on. But if is a number every digit to print in the new line.
Output number
Input string
Output string
HTML
<!Doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Exercises in JS</title>
<script src="exercises.js"></script>
<body>
<label for="myText">Input array:</label>
<input type="text" id="myText">
Submit
<br/>
<br/>
<label for="myText2">Input for delete:</label>
<input type="text" id="myText2">
Submit
</body>
</head>
</html>
Javascript
window.onload = function(){
inputBox =document.getElementById("myText");
btn = document.getElementById('sub');
inputBox2 = document.getElementById("myText2");
btn2 = document.getElementById('sub2');
btn.addEventListener("click",function(event){
event.preventDefault();
saveArr(inputBox.value);
});
btn2.addEventListener("click",function(event){
event.preventDefault();
removeItemAndprintNewArray(inputBox.value, inputBox2.value);
});
function saveArr(arr) {
var rv = [];
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
function removeItemAndprintNewArray(rv, number) {
var tmp = [],
st = "";
for(var index in rv){
if(rv[index] !== number){
tmp.push(rv[index]);
}
}
for (var i = 0; i < tmp.length; i++){
if (typeof(tmp[i]) == "String"){
st += tmp[i];
console.log(st);
}
else if (typeof(tmp[i]) === "Number"){
st += tmp[i];
console.log(st[i]);
}
}
}
}
Javascript automatically makes type conversations, and if conversation fails it returns NaN value instead of throw exception. Let's use it)
Small example
var arr = [12, "asd", 4];
arr.forEach(function(item) {
console.log(item - 0);
});
So you can check on NaN, don't forget that you should use special function isNaN()
var arr = [12, "asd", 4];
arr.forEach(function(item) {
if(isNaN(item - 0)) {
//do what you want with string
console.log("string");
};
else {
//do what you want with Number
console.log("number");
}
});

how to do a printer-like text field using javascript OOP

I'm doing a printer-like text field which could show the letter one by one. I could realize it just use a function and load it as simple like:
html---
<div id="myTypingText"></div>
js---
<script>
var myString = "Place your string data here, and as much as you like.";
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += myArray.shift();
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
But I want to do more advanced, I want to let the user to change the speed and change the text, so I wrote the following one but it went wrong, why? help me .thx.
html----
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
js----
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
this.loop = function (){
if(this.len > 0 ){
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
You need to use an anonymous function in the interval if you want the loop function to be executed in the context of the Printer object. Also you need to check the length of the array each time as the len property won't be updated when the array is shifted.
function Printer() {
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.loop = function () {
if (this.myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin() {
var test = new Printer();
setInterval(function () {
test.loop()
}, test.tempo);
}
See the working fiddle
Here's another approach. Your fundamental problem was with using the this keyword. You have to remember that when you enter another function scope, the this keyword changes. You'll notice here that I cache or save 'this' to equal that, then use that new 'that' value in the function. Plunker
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
var that = this;
this.loop = function (){
if(that.myArray.length !== 0 ){
document.getElementById("myTypingText").innerHTML += that.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
</body>
</html>

Prototype issue - How do I check for links on an input field and check for the length of that input field?

I sort of started coding for this. It's almost working.
My goals:
1) Check for the length or url's entered in a field (the total length) and reduce each link's length by 20 if the length is greater than 20
2) Determine the characters left in an input field
The javascript in profile.js (prototype):
function checkurl_total_length(text) {
var text = "";
var matches = [];
var total_length = 0;
var urlRegex = /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
text.scan(urlRegex, function(match){ matches.push(match[0])});
for (var index = 0; index < matches.length; ++index) {
item = matches[index];
reduce_length = matches.length*20;
if(item.length>20) {
total_length = total_length + item.length - reduce_length;
}
else {
total_length = total_length + item.length;
}
}
return total_length;
}
function count_characters(field){
var limitNum=140;
var link_length = 0;
if(checkurl_total_length(field.value)!=0) {
link_length =link_length+ checkurl_total_length(field.value);
}
else {
link_length = 0;
}
limitNum = limitNum+link_length;
if( link_length !=0 ){
$("links").update("with links");
}
left = limitNum-field.value.length;
$("count").update(left);
}
THE HTML
<!DOCTYPE HTML>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>JUST A TEST FILE</title>
<script src="prototype.js" type="text/javascript"></script>
<script src="profile.js" type="text/javascript"></script>
</head><body>
<h1>
CHARACTERS COUNT
</h1>
<div class="container_24">
<h2 id="title2">
TESTING
</h2>
<div class="grid_24">
<div id="count"></div>
<br /s>
<div id="links"></div>
<form >
<textarea wrap="hard" onpaste="count_characters(this);" onkeyup="count_characters(this);" onkeydown="count_characters(this);" id="updates" onfocus="count_characters(this);" name="test"/> </textarea>
<input type="submit" value=" " name="commit" disabled=""/>
</form>
</div>
</div>
<!-- end .container_24 -->
</body></html>
Counting characters left is working but checking for url and the length of the url isn't. Any hints on why this isn't working?
not sure, but should this be
checkurl_total_length(field.value!=0) // ) != 0

Categories