Adding splitted values in loops - javascript

I suggest u look at this picture, and then u look at the code I have written:
function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
for(i = 0; i <= splitted.length; i+=1) {
document.getElementById("resultNumberTotal").value = splitted[i];
}
}
I am taking the value from the box which says "Enter list of numbers and/or words" and I am splitting it. I split it so I have all the numbers like this "1 2 3" and so I can add them. I use the for loop for that. The for loop goes through every number and then it adds it. But when I press the button, it shows me undefined.
Why am I getting undefined?

function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
//make sure that the values are in a number format
document.getElementById("resultNumberTotal").value = splitted.reduce(function(a, b) {return Number(a) + Number(b);}, 0)
}
for the best practice make sure that allow number only for the input fields :) good luck

You need to somehow add the numbers up, either using the += operator, or by using something like .reduce() as I have done below.
function addNumbers() {
var val = document.getElementById("listInput").value;
document.getElementById("resultNumberTotal").value = val.split(" ").reduce(function(runningTotal, currentArrayElement) {
// make sure the value they typed is a number
// if not, fail gracefully and simply ignore it
if (!isNaN(Number(currentArrayElement))) {
// if it is a number, add it to the running total
runningTotal+= Number(currentArrayElement);
}
return runningTotal; // return the running total
}, 0); // start with 0 as the initial value for runningTotal
}
<input type="text" id="listInput" placeholder="insert values here..." style="width: 300px;" />
<button onclick="addNumbers()">Add Numbers</button>
<br/>
<br/>
<hr/>
Number Total: <input id="resultNumberTotal"/>

You are getting undefined, because you are displaying the value of the last element of the array and not doing the Sum as you mentioned in the question.
Following code always overrides the value of resultNumberTotal by the value of splitted[i]. Since, your for loop iterates for i <= splitted.length it reaches the index which doesn't exist in the array, when you get a property which doesn't exist on an object, you get undefined
for(i = 0; i < splitted.length; i+=1) {
document.getElementById("resultNumberTotal").value = splitted[i];
}
So, for doing the sum, you need to make the code like
function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
var total = 0;
for(i = 0; i < splitted.length; i++) {
var numberValue = +splitted[i];
if(!isNaN(numberValue)){
total = total + numberValue ;
}
}
document.getElementById("resultNumberTotal").value = total;
}

Related

Luhn Check Javascript

I am attempting to have someone input there credit card number and validate if it is a valid number by doing the Luhn Check. I want to be able to check it if they input the whole card number as one big string or if they put spaces in it. In my function validate though I keep getting an error message that there is an illegal return statement for my total variable. Here is my current code.
<script type="text/javascript">
function validate(numbers) {
var sum;
var sum1;
var total;
for (i = 0; i < numbers.length; i++) {
if (numbers.length % 2 == 0) {
sum += numbers[i];
}
else
if ((numbers[i] * 2) >= 10) {
sum1 += numbers[i] - 9;
}
else
sum1 += numbers[i];
}
total = sum + sum1;
return total;
}
function cardnumber() {
var cardnumber = document.getElementById("input").value;
var numbers = cardnumber.split(" ");
var out = "";
for (i = 0; i < numbers.length; i++) {
out += validate(numbers[i]);
if (out % 10 == 0)
return true;
}
}
function getOutput() {
if (cardnumber()) {
alert("You card is valid.");
}
}
</script>
<body>
<h1>I will validate a credit card number</h1>
Card Type:
<input type="radio" id="c1" value="Visa">Visa</input>
Card number: <textarea id="input" style="vertical-align: middle;"></textarea></br>
<input type="button" value="Submit" onclick="getOutput()" /></br></br>
</body>
Your function validate is missing an opening curly brace after the for loop. This made your return statement outside of your function and since a return statement is invalid outside of a function it was an invalid return statement.
function validate(numbers){
var sum;
var sum1;
var total;
for (i=0; i<numbers.length; i++) { // this previous curly brace `{` was missing
if (numbers.length%2==0){
sum += numbers[i];
}
else
if ((numbers[i]*2)>=10){
sum1 += numbers[i] -9;
}
else
sum1 +=numbers[i];
}
total = sum + sum1;
return total;
}
EDIT WITH MORE CORRECTIONS:
There is quite a bit more wrong with the formatting of you functions you also need to include opening and closing curly braces around your other else statements. I would suggest getting a code editor like VS Code and downloading an extension similar to Bracket pair colorizer 2. It will highlight paired brackets together. This will help you with your formatting.
function validate(numbers){
var sum;
var sum1;
var total;
for (i=0; i<numbers.length; i++) {
if (numbers.length%2==0){
sum += numbers[i];
}
else {
if ((numbers[i] * 2) >= 10) {
sum1 += numbers[i] - 9;
}
else {
sum1 += numbers[i];
}
}
}
total = sum + sum1;
return total;
}
function cardnumber(){
var cardnumber= document.getElementById("input").value;
var numbers = cardnumber.split(" ");
var out ="";
for (i = 0; i < numbers.length; i++) {
out += validate(numbers[i]);
}
if (out %10==0)
return true;
}
function getOutput() {
if (cardnumber()) {
alert("You card is valid.");
}
}
These are all the changed lines (the left is new code and the right side is the old code):
Tips for completion
validate function
So, currently if you console.log your numbers are strings when they pass into the validate function. This is fine when they are sent into validate, but when you add the numbers at index i (i.e. numbers[i]) you should use parseInt(numbers[i], 10) to turn them into numbers, so for example sum += parseInt(numbers[i], 10); the same applies when adding to sum1. The other thing to note is that saying var sum will make sum equal the undefined value. When you add a number or string to an undefined value some unexpected things will probably happen, so since you need your sums and totals to be numbers you should instead initialize your sums and totals at 0. Like so:
var sum = 0;
var sum1 = 0;
var total = 0;
The only other thing wrong with your validate function is that your are checking if numbers.length%2==0 which instead you should be checking if i%2==0. You may have to think about why for a moment, but one thing you may notice is the length of numbers never changes during the iteration of the loop where as i does change at each step.
cardnumber function
Your out variable needs to be initialized to zero. Your cardnumber can instead be split by spaces and then joined by the empty string. This handles if the user accidentally types multiple spaces. Then since you join your split array you no longer would need a for loop.
var numbers = cardnumber.split(" ").join('');
var out =0;
out += validate(numbers);
Lines that need changing somehow
Here's a difference of the lines of the old code that where incorrect and need to be changed somehow. I'm not giving you the completed code, but hopefully this will be sufficient to help you figure out the rest on your own (I feel I shouldn't give you all of the solution due to some degree of academic integrity. I would feel I robbed you the opportunity to learn more if I don't at least let you think through and type it out on your own.). If you are wondering what needs to be changed on a specific line that is highlighted red all of it should be above, so best of luck.

Searching for number inside of an array

Forgive me, I am not quite skilled and fairly new to the language and programming practices. I am creating a button which prompts the user to enter a number once the number is entered, I create a for loop that iterates through the same amount as the number. For example, the user enters 4 and the screen will display 0 1 2 3 and then I have a button that asks the user to enter a number to see if that number exists in the previous array. So if the user entered 3 it would dispay "it exists" if they entered 5 it would display "number not found". Should I create an array to store the iterations and then run that array through a function that searches for the number. Looking for guidance, thank you for the help guys.
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"),10);
// Set up a string that will become the output.
var output = " ";
// loop through given number
for(var i = 0; i < n; i++){
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber(){
var sn = parseInt(prompt("Search for number"),10);
for(var j = 0; j < sn; j++){
}
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick ="findNumber()">Click!</button>
Make your n variable global
Than compare if sn is higher than n
var n; // Make it global
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
n = parseInt(prompt("Please enter a number"), 10);
// Set up a string that will become the output.
var output = " ";
// loop through given number
for (var i = 0; i < n; i++) {
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber() {
var sn = parseInt(prompt("Search for number"), 10);
var isHigher = sn > n; // n is now accessible in this function
var message = isHigher ? "Not found" : "Number found!";
alert( message );
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick="findNumber()">Click!</button>
To search an array, use the indexOf() method of a JavaScript array. The original post gives an example populating the array with myArray[x]=x, creating options pointed out by other solutions. Presuming you want to search a more general case of an array, you could use indexOf directly or define a function that returns true or false:
function inArray(myArray, queryValue) {
return myArray.indexOf(queryValue) > -1;
};
Arrays in JavaScript are objects with some additional methods like pop(), indexOf(), etc. JavaScript objects are associative arrays; this solution only applies to Array objects. Array objects are constructed with the [] literal or the Array() constructor. Arrays can only have properties named by ints, unlike other JavaScript associative arrays. See Eloquent JavaScript.
In this theoretic example, it's true that you only need to check if the second number entered is smaller than the first number. If you want to search for a number in an array of any numbers, you can use the javascript indexOf function. See example below:
var arr = [1,6,77,888];
if (arr.indexOf(66) > -1) {
alert('number is in array');
} else {
alert('number is not in array');
}
There are a couple of ways to do this. For the sake of simplicity, I'll use a global variable here.
// A global variable to store user input
var userInput;
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"),10);
// Store the user's input to our global variable
userInput = n;
// Set up a string that will become the output.
var output = " ";
// loop through given number
for(var i = 0; i < n; i++){
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber(){
var el = document.getElementById("result");
var sn = parseInt(prompt("Search for number"),10);
// If number is within the range
if (sn < userInput) {
el.textContent = "it exists";
}
// If number is not within the range
else {
el.textContent = "number not found";
}
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick ="findNumber()">Click!</button>
<p id="result"></p>

Multiplication table in JavaScript returns undefined with multiplication number WHY?

Script part:
function makeTable() {
var num = document.getElementById('Numb').value;
var myPara = document.getElementById('para');
var tb = new Array();
for (var i = 1; i <= 10; ++i) {
var result = num * i;
tb.push(result);
tb[i] = tb[i] + "<br>";
}
tb = tb.join("");
myPara.innerHTML = tb;
}
HTML part
<input type = "number" value = "" id = "Numb" placeholder = "TABLE NUMBER">
<input type = "button" value = "Give me Table" onClick = "makeTable()">
<p align = "center" name = "myownpara" id = "para"> </p>
When I run this code it returns undefined with first element of array
Arrays start at 0, not 1. Change it to var i= 0 in your 'for' loop and add the line if(i==0) continue; right after starting your for loop to skip over 0.
Actually, another problem is your array. It might be best to initialise your 0th element because you are looking at it later. Change new Array() to new Array(""): To already add a 0th element so you dont have to when you use my aforementioned continue statement.
Update, refinement
I refined your code below. I don't know why you are using an array, as you want to output a string anyway. So Just add it to the string for every element as it reduces the amount of things you need to do. The below will work. I also removed you 'myPara' as you only use it once anyway, so theres no point in saving it.
Also note that in this case we don't need to start at 0 as we don't have an array to add to.
function makeTable() {
var num = document.getElementById('Numb').value;
// lets use a string since thats what you want in the end and its easier.
var tb = "";
for (var i = 1; i <= 10; ++i) {
// add it to the string. I reduced the number of steps as its so simple
// You don't need to save stuff in vars for this thing.
tb += (num * i) + "<br>";
}
document.getElementById('para') = tb;
}

Get the value for each control from a list of elements?

I'm struggling to get the input value from a control in JavaScript, and I think it may have something to do with the collection of controls I'm looping through.
My page consists of many input controls with decimals in them. I'm only interested in controls starting with the name 'txtinput', and I need to tally up the values in each one. However, when I do this with the code below, all I seem to be getting out is a JSON looking string for each element.
function TallyPoints() {
var eles = [];
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
total += document.getElementsByName(inputs[i].name)[0].value;
}
}
alert('Total: ' + total.toString());
};
What I end up with is a value that looks like this:
Total: 0{"enabled":false,"emptyMessage":"","validationText":"333.33","valueAsString":"333.33","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"333.33"}{"enabled":false,"emptyMessage":"","validationText":"5.66","valueAsString":"5.66","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"5.66"}
Any ideas?
You probably want parseFloat() so your addition works properly (fiddle):
var inputs = document.querySelectorAll("input[name^=txtpoints]");
var total = [].reduce.call(inputs, function (p, c) {
return p + (parseFloat(c.value) || 0);
}, 0);
See also parseInt(), isNaN(), and Array.prototype.reduce()
Try this:
function TallyPoints() {
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
var val = parseFloat(inputs[i].value);
if (!isNaN(val)) {
total += val;
}
}
}
alert('Total: ' + total);
};
parseFloat is needed to convert the input from a string to a number, so that + will do addition rather than concatenation. There's no need to use getElementsByName, since you already have the element in inputs[i]. There's no need to use total.toString(); concatenating a number to a string converts it automatically.
The if (!isNan(val)) test skips over the inputs that don't contain numbers.
You could also use document.querySelectorAll('input[name^=txtpoints]') to find the relevant input elements in one step.

calculating average using for loop in javascript

function averageCalculator (numvalues) {
for(i=0, i <= numvalues, i++>) {
var score = prompt("input the score")
result1 += score;
}
alert(result1 / 3);
}
this function is later triggered by a button with onclick="averageCalculator (2)
<input type="button" value="Click for the average" onclick="averageCalculator (2)">
any ideas why its not working? it should prompt you for 2 values and then alert you with the average. not sure whats wrong.
Your code has multiple issues. The for loop is not well formatted and you need to terminate statements with a semi-colon. Also you need to declare variables. And your loop will run numvalues+1 times which is why i removed the = in your loop. Also if you want to calculate an average you want to divide by numvalues.
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += score;
}
alert(result1 / numvalues);
}
On top of the invalid syntax you will run into a common "problem" with javascript here. The inputs are treated as strings and instead of being added they will be concatenated. Providing 2 and 2 as scores will result in 11. 2 concatenated with 2 = 22 / 2 = 11. You need to cast the value to a number explicitly before adding them together:
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += Number(score);
}
alert(result1 / numvalues);
}
Above code will correctly return 2
The syntax of your for-loop is wrong:
for(i=0, i <= numvalues, i++>) {
should be
for(i=0; i <= numvalues; i++) {
Tip: Also, it's better to use
for(var i=0; i <= numvalues; i++) {
since then i will be a local variable instead of a global one.
Try like this
for(var i=0; i <= numvalues; i++){}
An alternative solution (using a functional programming libary, like Underscore.js):
function averageCalculator(numValues) {
var numbers = _.map(_.range(numValues), function(element) {
return +prompt('input the score');
});
var result = _.reduce(numbers, function(memo, number) {
return memo + number;
}, memo);
alert(result / 3);
}
While a little bit more complicated (and less efficient), you'll get rid of loops altogether.
EDIT
The +prompt('input the score') does effectivly the same as Number(prompt('input the score')).

Categories

Resources