JavaScript while loop simple JS - javascript

i've got a question. I've started this course on Udemy for JavaScript and we got to "while" loops. Now i get what while loops do, and i tried to create a simple number guessing game, but the thing back fired on me.
Here's the code:
var num = Number(prompt("What is the secret number?"));
while(num !== 354){
var num = prompt("Guess the number!!!");
}
alert("Correct number!!");
I've tried without Number () in var, i've tried with if and else, but it's not working. I mean it works, but when i type in any number it gives me "Guess the number!!!" info, but when i type in number "354" it gives me the same information. Now this is not a project, just exercise, but don't understand...
Thank you in advance guys

This is a data Type issue. Specifically your input is still capturing a string and the while loop is expecting a valid type Number.
A simple method to ensure your data type is always what you need in this case would be parseInt()
Other methods:
Casting: using the Number() function. Note: this has some limitation with Strings, particularly spaces.
parseFloat(): This will take an argument and spit out the Float value.
I added this to the num variable within while()
var num = Number(prompt("What is the secret number?"));
while(parseInt(num) !== 354){
var num = prompt("Guess the number!!!");
}
alert("Correct number!!");

Replace the strict comparison with type-converting one. This way your comparison captures both numeric and string data types.
Also, you don't really need to redeclare your variable in the loop body, you can safely omit var there then.
var num = prompt("What is the secret number?");
while(num != 354){
num = prompt("Guess the number!!!");
}
alert("Correct number!!");

This code is working (i used similar and edited it), but that one is not, where is the difference:
var answer = Number(prompt("What is the secret number?"));
while(answer !== 354){
var answer = prompt("Guess the number!!!");
}
alert("Yay, we made it!!!");

Related

Why do I get undefined here?

function myFunc() {
var word = document.getElementById("Text1").value;
var num = parseInt(document.getElementById("Text2").value);
var numstr = num.split(",");
var wordstr = word.split("");
for (i = 0; i < word.length; i++) {
}
document.getElementById("myDiv").innerHTML += (wordstr[(numstr[i])-1]);
}
did I parseInt incorrectly? I've tried toString(), with ParseInt it doesn't do anything and without it I get 'undefined'
The parseInt() function parses a string and returns an integer.
You check your input with id "Text2" and show your HTML here to clearify the issue.
Without knowing more about your problem, it looks like you are misunderstanding how parseInt() works. Despite the misleading name, it will read your string character by character, attempting to create an integer. It will stop as soon as it finds a character that can't be part of an integer.
If you pass it "1,2,3,4" then it will read the 2 fine, but as a comma cannot be parsed as part of an integer, it will return the number 2. It doesn't make sense to call split on a number.
As others have said, you really need to give us more details for us to be able to help, but I suspect a large part of the problem is not understanding what some of these functions do.
Maybe you could explain what you're trying to achieve, then we can help you get there. Right now, your code isn't clear enough without extra information.

Slicing a string from a textbox

I am trying to take a string entered by user from a textbox. Check the length of that string and if the string is over a given number perform the slice operation on it.
Here's what I came up with but my code does nothing. Checked console, no errors given.
html:
<form id="slice">
Enter a pharse:<input type="text" id="text_box_2"><br>
<input type="button" value="slice" onclick="Slice()">
Result: <input type="text" id="slice_result"><br>
</form>
Javascript function:
function Slice(){
var UserString = document.getElementById("text_box_2").value;
var UserStringValue = UserString.length;
var Result = Userstring.slice(1,6);
if (UserStringValue > 6){
document.getElementById("Slice_result").value = Result;
}
else{
alert("Please enter a longer phrase.")
}
}
what or where did I go wrong?
Be mindful of case-sensitivity.
This:
var Result = Userstring.slice(1,6);
Should be using UserString (capital "S") as defined earlier in your code.
Next, the input ID should be all lowercase, slice_result, to match to HTML, but your code uses different casing:
document.getElementById("Slice_result")
Here's a working JSBin with these fixes.
EDIT: As JaromandaX mentioned in the comments, if you want to take the first 6 characters you should use slice(0, 6).
from cursory reading of your code. it seems caused by this line
var Result = Userstring.slice(1,6);
and also this one
document.getElementById("Slice_result").value = Result
it should be
var Result = UserString.slice(1,6);
and
document.getElementById("slice_result").value = Result
Usually use of the following
var Value = $('#input_id').val();
will pull the requested information for you.
You can also set up arguments for your slice function and pass in the value when you run onclick();
I'd also note that slice() is a current js function, though your implentation with the capital 'S' is some what different, it may be better practice to change that name a bit.

jQuery won't count up variables

I have a little problem with my jQuery script: instead of counting up all variables, the script puts them next to each other. How do I count up the variables? (I am new to jQuery, so maybe I overlooked something or made a stupid mistake).
This is the line of code that should count up the variables.
totalcost = ((commissioncost + paypalcost) + qrticketcost);
http://jsfiddle.net/bsuh5q8k/1/
Thanks.
Often when you retrieve a value from a field using jquery's .val(), you'll get the string value (String type) instead of the numeric value you desire here. For instance, the field value may be 37.50, but you're getting "37.50" from .val()
So when you do this:
commissioncost = $('input[name=price]').val();
You'll get the String value.
So instead, try this:
commissioncost = Number($('input[name=price]').val());
This will convert/cast the value into a Number for you.
Also, a word of caution: just be sure whatever value is in that field, it can be evaluated as a Number, otherwise comissioncost will equal "NaN" (not a number) and will give you the same grief you're experiencing now. The rudimentary method to check if the type conversion was successful is:
commissioncost = Number($('input[name=price]').val());
if(isNaN(commissioncost)){
// oops, value wasn't a number!
}else{
// hooray! value was a number (most of the time - but that's a longer discussion)
}
commissioncost is being treated as a string. So when you add it thinks you're wanting to concatenate.
When you pull it from the input, explicitly tell Javascript that it's a number/float.
commissioncost = parseFloat($('input[name=price]').val());

Make parseFloat convert variables with commas into numbers

I'm trying to get parseFloat to convert a userInput (prompt) into a number.
For example:
var userInput = prompt("A number","5,000")
function parse_float(number) {
return parseFloat(number)
}
When userInput = 5,000, parse_Float(userInput) returns 5.
However, if the user was inputting a value to change something else (ie: make a bank deposit or withdrawl) Then I to work properly, parse.Float(userInput) needs to return 5000, not 5.
If anyone could tell me how to do this it would help me so much. Thanks in advance.
Your answer is close, but not quite right.
replace doesn't change the original string; it creates a new one. So you need to create a variable to hold the new string, and call parseFloat on that.
Here's the fixed code:
function parseFloatIgnoreCommas(number) {
var numberNoCommas = number.replace(/,/g, '');
return parseFloat(numberNoCommas);
}
I also renamed the function to parseFloatIgnoreCommas, which better describes what it does.
This is the function I use to scrub my user inputted numbers from a form. It handles anything a user may put in with a number like $ or just accidentally hitting a key.
I copied the following out of an object:
cleanInput : function(userValue){
//clean the user input and scrub out non numerals
var cleanValue = parseFloat(userValue.replace(/[^0-9\.]+/g,""));
return cleanValue;
},
To make it non-object just change the first line to cleanInput(){....
I have put together info from the comments to form a basic answer:
The answer seems to simply be to set parse_float to run :
number.replace(/,/g, "")
return parseFloat(number)
The complete code would look like this:
var userInput = prompt("A number","523,000,321,312,321")
function parse_float(number) {
number.replace(/,/g, "")
return parseFloat(number)
}
returns: 523000321312321

jQuery: Content of html element is interpreted as a string, not an integer

When somebody is liking a comment on my website, a "1" is added at the right of the number where the amount of likes are shown, but when they click dislike, it does correct math.
For example:
14 + 1 = 141
14 - 1 = 13
jQuery
var elem = $('.like_button'), //Like button
num = $('.num_likes'), //Get the element: number of likes
oldnum = num.html(); //Number of likes
if(elem.html() == "Like") {
elem.html("Dislike");
num.html(oldnum+1); //Adds one like after liking it
} else {
elem.html("Like");
num.html(oldnum-1); //Deletes one like after disliking it
}
I really wonder why disliking works but liking not.
Why does javascript interpret the value of the num element as a string, even though it is a number? Any tips for me?
Because JavaScript interprets num.html() as text. The + sign for string in javascript means concatenation, but - doesn't mean that so in that case javascript realizes you want to do numeric calculation. That's why it works with -
You should cast oldnum to an integer with parseInt().
You need to cast oldnum to a number:
if(elem.html() == "Like") {
elem.html("Dislike");
num.html(Number(oldnum)+1); //Adds one like after liking it
} else {
elem.html("Like");
num.html(Number(oldnum)-1); //Deletes one like after disliking it
}
Alternatively, +oldnum does the same thing as Number(oldnum).
Javascript is interpreting the text on your page as a string. This is because that's what text on a page normally is. Take for example:
<span id="berliner">I am a jelly donut.</span>
<script LANGUAGE="Javascript">
document.getElementById("berliner").innerHTML;
// it only makes sense that this be a string, right?
</script>
Now, in JS, you use the + sign for two things: adding numbers, or putting one string after another.
var addingnumbers = 1+1;
// adding numbers, what you want
var a = "I am";
var b = " a jelly donut";
var addingstrings = a+b;
// adding strings, which you don't want.
As such, the html was interpreted as a string like it normally should be, but in this case shouldn't be. And adding the string to the other string just appended it to the end, rather than doing math. There is an easy solution: convert the innerHTML to a number by multiplying it by 1. Multiplying can't be done to a string, so JS will change it to number form, prepping it to be added to something else.
var oldnum = num.html()*1; // done! The multiplying has changed it to a number.
And if you ever do want to change it back to a string, you can do the reverse with the toString() function.
var aNumberToStartOutWith = 3;
var aStringToEndOffWith = aNumberToStartOutWith.toString();

Categories