New to Javascript, im wondering why - javascript

My code doesnet add number like 2+2=4 , its adds it like 2+2=22.
I was wondering how I could change this so that it recognizes that my variables are numbers.
var gra=0;
var graTwo=0;
var graThree=0;
var stu = prompt("Who are you grading?");
var gra = prompt("Oh, what is " +stu+ "'s grade?")
if(gra>80) {
alert("Congrats, " +stu+ ". Have a gold star!")
}
else {
alert("Wow, thats awful " +stu+ ", try again")
};
var stuTwo = prompt("Who are you grading?")
var graTwo = prompt(" Oh, what is " +stuTwo+ " 's grade?")
if(graTwo>80) {
alert("Congrats, " +stuTwo+ ". Have a gold star!")
}
else {
alert("Wow, thats awful " +stuTwo+ ", try again")
};
var stuThree = prompt("Who are you grading?");
var graThree = prompt("Oh, what is" +graThree+ "'s grade?")
if(graThree>80) {
alert("Congrats, " +stuThree+ ". Have a gold star!");
}
else {
alert("Wow, thats awful " +stuThree+ ", try again")
};
var add = (gra+graTwo+graThree);
alert(add)
alert("The average grade of your class is ")

You aren't having trouble because of the pluses. You are having trouble because you are assigning graThree to a prompt, which is a string. Use parseInt as the other answer suggests.
Also, you are prompting prompt("Oh, what is" + graThree+ "'s grade?") when you should be using the variable stuThree.

You need to use parseInt or parseFloat.

The prompt function returns string types so your addition concatenates strings instead of adding numbers.
You should always be sure of your variable types before performing any action on them.
Javascript can be a little too nice sometimes.

Related

How do I remove the last character in some text being copied from one field to another using JavaScript or other methods?

I have a form that I created to make my work easier and recently figured out how to make certain fields automatically generate a comma and separates after 5 letters or numbers have been typed into it (CPT codes for medical claims that I have to look up) using the same coding you would for putting spaces between numbers. I also have coding here that would force letters to be capitalized since I'm a bit OCD about that stuff for work:
<input name="checkbox24" type="checkbox" id="checkbox24" onClick="FillDetails24(this.form);" /><span style="background-color:yellow">CPT</span>
<input type = "text" size="8" class = "uc-text-smooth" name="textfield24" id="textfield24" />
<script language = "JavaScript">
const forceKeyPressUppercase = (e) => {
let el = e.target;
let charInput = e.keyCode;
if((charInput >=97) && (charInput <= 122)) { // lowercase
if(!e.ctrlKey && !e.metaKey && !e.altKey) { // no modifier key
let newChar = charInput - 32;
let start = el.selectionStart;
let end = el.selectionEnd;
el.value = el.value.substring(0, start) + String.fromCharCode(newChar) + el.value.substring(end);
el.setSelectionRange(start+1, start+1);
e.preventDefault();
}
}
};
document.querySelectorAll(".uc-text-smooth").forEach(function(current) {
current.addEventListener("keypress", forceKeyPressUppercase);
});
document.getElementById('textfield24').addEventListener('input', function (g) {
g.target.value = g.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{5})/g, '$1, ').trim();
});
</script>
When I use the checkbox, it automatically generates pre-written text using the following JavaScript:
function FillDetails24(f) {
const elem = f.Reason;
const x = f.Action;
const y = f.Resolution;
f.Reason.value += ("Verify CPT " + f.textfield24.value + ". " + '\n');
f.Action.value += ("Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. " + '\n');
f.Resolution.value += ("Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT " + f.textfield24.value + ". " + '\n' + '\n' );
}
However, because of the way that I put it together, the end result would be, "Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT V2020, 99213,. " The extra comma at the end is driving me nuts.
Since it was my first time using this
document.getElementById('textfield24').addEventListener('input', function (g) {
g.target.value = g.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{5})/g, '$1, ').trim();
});
with this
function FillDetails24(f) {
const elem = f.Reason;
const x = f.Action;
const y = f.Resolution;
f.Reason.value += ("Verify CPT " + f.textfield24.value + ". " + '\n');
f.Action.value += ("Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. " + '\n');
f.Resolution.value += ("Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT " + f.textfield24.value + ". " + '\n' + '\n' );
}
I'm not certain how I can code it to eliminate the last comma generated at the end when it pulls the value of textfield24.
This is a very long, complex html form I've coded by hand for fun and for personal use at work for 4 years with only a couple years of HTML training and a little bit of JavaScript I learned in high school forever ago and I've been busting my butt to make this work perfectly so that I only have to tweak the pre-written stuff when things change at work.
I'm at a loss on how to continue. Any suggestions?
You can replace with regex /,$/.
f = { textfield24: { value: 'V2020, 99213,'} }
console.log(f.textfield24.value);
console.log(f.textfield24.value.replace(/,$/, ''));
function FillDetails24(f) {
const elem = f.Reason;
const x = f.Action;
const y = f.Resolution;
f.Reason.value += ("Verify CPT " + f.textfield24.value + ". " + '\n');
f.Action.value += ("Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. " + '\n');
f.Resolution.value += ("Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT " + f.textfield24.value.replace(/,$/, '') + ". " + '\n' + '\n' );
}
you can use substring to remove the last comma, but you have to make sure that the last comma always be there. otherwise, you're gonna remove something else.
const example = "Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT V2020, 99213,. ";
const result = example.substring(0, example.lastIndexOf(",")) + ".";
console.log(result);

Random Fruit guessing Game

I'm in my second week of Javascript and the task we've been given is to create a guessing game.
The steps we've been given are:
Prepare a list of your favourite fruits and store it in an appropriate data structure and have the computer select a random fruit as the secret word.
Base on the selected fruit give the use a hint like the example below. you can use prompt, alert or console.log to show the hint
for example if the secret fruit is "banana"
hint: it's 6 characters long. Starts with b and ends with a. guess the fruit.
instead of typing out the hint manually for every fruit. try to use a template string and programmatically work out the starting letter, ending letter and how many characters long.
Allow the user to guess the fruit repeatedly until they guess correctly. keep track of the number of guesses.
Congratulate the user and display number of attempts they made.
I've been sitting on this for awhile and have tried shifting my code around. I know I'm close but would love some pointers or tips.
This is what I have so far:
var fruits = ["kiwi", "banana", "apple", "strawberry", "watermelon", "orange"];
var ranNum = Math.floor(Math.random() * fruits.length);
var secretFruit = fruits[ranNum];
var userPrompt = prompt("Guess the fruit");
var guess = 1;
while (userPrompt !== secretFruit) {
prompt(
"hint: it's " +
secretFruit.length +
" characters long. Starts with " +
secretFruit[0] +
" and ends with " +
secretFruit.slice(-1) +
". guess the fruit."
);
guess++;
}
if (userPrompt == secretFruit) {
alert(
"Congratulations you guessed the fruit, and it took you " +
guess +
" guesses"
);
}
Any help would be great, thank you.
Two things wrong: your while loop and hint prompt.
First of all, your while loop will continuously keep prompting without ever checking whether the answer was correct, because you have left the if statement outside of the loop.
Also, the if statement should be before the hint statement otherwise the person will always have to try again even if they got the answer correct.
Secondly, your hint prompt is never actually recorded. This means that despite getting the answer correct, the code never actually records it.
Also, I suggest adding a break statement so that the game ends.
This is a working version of your code:
var fruits = ["kiwi", "banana", "apple", "strawberry", "watermelon", "orange"];
var ranNum = Math.floor(Math.random() * fruits.length);
var secretFruit = fruits[ranNum];
var userPrompt = prompt("Guess the fruit");
var guess = 1;
while (userPrompt !== secretFruit) {
if (userPrompt == secretFruit) {
alert(
"Congratulations you guessed the fruit, and it took you " +
guess +
" guesses"
);break; //break statement here stops infinite loop when correct
}
userPrompt = prompt(
"hint: it's " +
secretFruit.length +
" characters long. Starts with " +
secretFruit[0] +
" and ends with " +
secretFruit.slice(-1) +
". guess the fruit."
);
guess++;
}

How can I get a true random from an array? Or should I do something else entirely?

I would like to display a different madlib each time a user clicks the submit button. Only needs to be clicked 3 times. I am using the functions below, but it doesn't seem all that random. I also have a snippet of the dogLib function that creates three madlibs and then calls the function above it to generate a random madlib string.
//Class: madlibGenerator.js
//----- Private Helper Functions -----
//Get Random: word strings for randam madlib
//Get Random: madlib string to display
function getRandomString(array) {
for(var i = array.length - 1; i>0; i--){
var j = Math.floor(Math.random() * (i+1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return this.word = array.pop();
}
//Set: set user input word string arrays into the getRandomString(array)
//Get: a final array of words to add to the madLib display strings
function getFinalWordArray(){
var prpN = getRandomString(this.properNouns);
var adjt = getRandomString(this.adjectives);
var noun = getRandomString(this.nouns);
var vrb = getRandomString(this.verbs);
return finalWordArray = [prpN, adjt, noun, vrb];
}
//Get Random Dog Lib
function getDogLib() {
//Get Random Dog Words
var dogWordsArray = getFinalWordArray();
//DogLibs
var dogLibOne =
"What is that " + dogWordsArray[1] +
" sound!" +
" Hey! " + dogWordsArray[0] +
"! You come " + dogWordsArray[3] +
" you crazy " + dogWordsArray[2] +
"!";
var dogLibTwo =
dogWordsArray[0] + "!! " +
dogWordsArray[0] + "!! " +
"Come " + dogWordsArray[3] +
" and lay on my clean " + dogWordsArray[2] +
" while your treat is still " + dogWordsArray[1] + "!";
var dogLibThree =
"My human comes home and takes me for a " + dogWordsArray[3] +
" where I sit on a " + dogWordsArray[2] +
" and get my " + dogWordsArray[1] +
" belly rubbed!";
//Make array of DogLibs
var dogLibArray = [dogLibOne, dogLibTwo, dogLibThree];
//Pick random dogLib string to display
finalDogLib = getRandomString(dogLibArray);
}
//Display: Random MadLib to console for now
function displayMadlib(pDisplayIDValue) {
if(pDisplayIDValue == "dogLib"){
//display
getDogLib();
console.log(finalDogLib);
}else if(pDisplayIDValue == "loveLib"){
//display
getLoveLib();
console.log(finalLoveLib);
}else if(pDisplayIDValue == "funnyLib"){
//display
getFunnyLib();
console.log(finalFunnyLib);
}
}
The code above isn't broken, it just doesn't produce a true random.
//Preferred Result: the program displays a different madlib each time the user clicks the submit button. The user only needs to click the button 3 times to get different madlibs, the fourth click clears the form and starts the program fresh.
Thank you!
I am open to any idea to make this a truly random madlibGenerator. Maybe counting number of clicks from a submit button?
So true randomness is going to be tough to achieve. Math.Random() from the javascript library isn't truly random as you've guessed, it's pseudo-random, meaning there is a pattern to it over a large number of inputs. Computers inherently can't really do true randomness, because they are always going to have to take some number, perform some sort of algorithm on it (these are usually "Mersenne Twisters" - fun wikipedia read), and spit out the result.
That said, I don't know exactly how to improve on what you've put into place here. With PRNG, a really large number of possible inputs can help a lot. If you want absolutely true randomness, the easiest way would probably be to hook into random.org's API (https://api.random.org/dashboard - developer license is free, limited to 1000 requests per day). Hooking into an API might be more work than you were planning on, but random.org uses (if I remember right) atmospheric noise and barometric pressure from the Earth to create their random numbers, so it's about as close to true randomness as you can possibly get.
I hope this helps!

Javascript assignment for school involving objects and Validation not working correctly

the past two days I've been really struggling on finishing this assignment.
The assignment goal is to create a javascript that takes in Student information until the user either hits cancel or enters in blank text.
the information gets validated every time the user enters information if it is valid, it is then saved to a Student Object Array.
Here is my code:
var Student =[];
// Validates Student Courses, loops through making sure they are equal to courseList values.
function validateCourses(courses){
var valid='';
var courseList = ['APC100','IPC144','ULI101','IOS110','EAC150','IBC233','OOP244','DBS201','INT222'];
alert(courses);
for(var i =0;i<courseList.length;i++){
var a = courses;
a.splice();
if(a[i]!==courseList[i]){
valid=false;
}
else{
valid=true;
}
}
return valid;
}
function formatingName(name){
var res ='',cap='';
res = res + name.charAt(0).toUpperCase();
cap = res + name.substr(1);
return cap;
}
// I'm having issues with this validation for the student id. the student id can only be xxx.xxx.xxx
function validateStudentID(sid){
var validate=0;
var patt1 = /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/;
var result = patt1.test(sid);
return result;
}
var courseSelect=[];
var tag=0;
// this displays what users are in what course depending on what the user enters
function code(coursecode){
for(var w = 0;w<count;w++){
for(var t = 0;t<Student[w].courses.length;t++){
var a = Student[w].courses;
a.splice();
if(a[t] == coursecode){
tag=1;
}
}
if(tag){
courseSelect.push(Student[w].fname + " " + Student[w].lname + " " + Student[w].id + " " + Student[w].email);
}
}
alert('List students registered in ' + coursecode + ' :\n\n' + courseSelect.join('\n'));
}
// main functions and validation calls
var userInput = "";
var i=0,count=0,j=4,flag=false;
var result='',courses=[];
var Student,validCourses;
do{
userInput = prompt("Please enter first name, last name,student ID,\n" +
"email and courses (speareted by ',').");
if(userInput != null && userInput !=''){
result = userInput.split(',');
for(var i=4;i<result.length && i < 10;i++){
courses.push(result[i].toUpperCase());
}
// VALIDATION OF STUDENT ID AND STUDENT COURSES */
while(!flag){
var valid = validateStudentID(result[2]);
alert(valid);
if(valid){
id = result[2];
flag=true;
}
else {
alert(Student.id + " is not valid Student ID!" + "\n" + "Please try again.");
flag=false;
}
validCourse = validateCourses(courses);
if(validCourse){
flag=true;
}
else {
alert( validCourse + " is not the course provided by the CPD program! \n Please try again");
flag=false;
}
}
if(flag){
Student.push({
fname:formatingName(result[0]),
lname:formatingName(result[1]),
id:result[2],
email:result[3].toLowerCase(),
courses:courses,
});
count++;
i++;
}
else {
Student = [];
}
}
}while(userInput != null && userInput !='');
alert('There are total '+ count + ' students registered');
var coursecode = prompt("Please enter course code: ");
code(coursecode);
Some of the most obvious problems in your code are:
You have a while(!flag) loop after the input section. That loop contains no other request to input anything. Therefore it will run endlessly if your validate* methods return false.
Your regular expression /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/ isn't doing what you want it to do. You can simplify it to just /^[0-9]{3}\.[0-9]{3}\.[0-9]{3}$/ as all you want to know is whether your input parameter sid contains three number blocks, each of length 3. You don't need any braces for that and escaping them via \(? would anyways be wrong. You also didn't escape your points via \., which is wrong as they would match basically any character. You should read up more about regular expressions.
Your loop in validateCourses looks wrong. Why do you assign courses to a new variable (it isn't copied to a) and then call splice()? Your following if condition is also wrong, as it assumes that a and courseList have equal length and that the positions of the courses would match. That's certainly not what you want. You should check for each course in course whether it is contained in courseList, e.g.: var notInCourseList = courses.filter(function(course) { return (courseList.indexOf(course) == -1); }); and then return (notInCourseList.length == 0);. A forEach loop would be an easy alternative. You should read some tutorials about that.
Similarly, I don't see any good reason for var a = Student[w].courses; a.splice(); in code(). Just check directly on Student[w].courses.
Slightly more working jsfiddle here.

Unable to clear the Input Fields

I have a very basic code. However I am not able to clear the of the Year with the id (userYOB) on clicking the alert ok. The code works only for the which asks for year. Its not just the clearing of but I also want to bring the place holder back once alert is clicked ok.
Thanks for help.
[fiddle] http://jsfiddle.net/vineetgnair/j8zjjj9r/26/
var d = new Date();
var currentYear = d.getFullYear();
function test() {
var userYearOfBirth = document.getElementById("userYOB").value;
var authorisedAge = 19;
var currentAge = parseInt(currentYear - userYearOfBirth);
//console.log(currentAge);
if (currentAge < authorisedAge) {
alert("You are not authorised to visit the site");
document.getElementById("userYOB").value = " ";
} else {
alert("Welcome to the site!");
userYearOfBirth = " ";
}
}
In else part say
document.getElementById("userYOB").value= " ";
instead of
userYearOfBirth = " ";
Because userYearOfBirth is a simple string so updating it doesn't update the value of textbox.
Please add the following lines after the else part,
document.getElementById("userYOB").value= " ";
document.getElementById("userMOB").value= " ";
document.getElementById("userDOB").value= " ";
This will clear the fields and bring back the placeholder. The reason why
userYearOfBirth = " "
doesn't work is because in the following line the variable actually holds the value not the element itself,
var userYearOfBirth = document.getElementById("userYOB").value;
It would be more advisable if you, replaced the above line with,
var userYearOfBirth = document.getElementById("userYOB");
now you have the reference to the element in the variable. You can easily change the elements value by,
userYearOfBirth.value = " ";
Personally, I prefer the latter method cause its less code. I hope this helps!! :)

Categories

Resources