value method not working function callback - javascript

I am creating a small program that returns the results of a mathematical equation. I have a number input field with the ID and CLASS "value1" (I've attempted to manipulate using both) that allows the user to put in a number value. I have another number input field that is disabled with the ID and CLASS "result1" that displays the results of the equation.
I have a button with the ID solution1_btn that when clicked is suppose to initiate the "multiples" function callback which takes "value1" as an argument.
When I replace "value1" which a physical number e.g. 1000, the results of the equation appears in "result1" without pressing solution1_btn, however when i put "value1" as the argument and press solution1__btn it does not work.
Below is the section of JavaScript code that I have narrowed the problem to and HTML.
JS:
// declare Euler1 assign it to function with parameter num
// click button
var solution1 = document.getElementById("solution1_btn");
// user entered value
//var value1 = document.getElementById("value1");
var value1 = document.getElementsByClassName("result1")[0].value;
//console.log(value1);
// result input field
var result1 = document.getElementById("result1");
function multiples(num) {
// declare sum assign it value 0
var sum = 0;
// declare a for loop that iterates while the counter "i" is less than num
for (var i = 0; i < num; i++) {
// if statement test whether the division remainder of 3 and 5 are equal to 0
if (i % 3 || i % 5 === 0) {
// assigns the value of i to sum
sum += i;
var newSum;
result1.value = newSum;
newSum = sum;
};
};
// returns the value of sum from the function callback argument 1000 etc.
return newSum;
};
var fix = value1;
solution1.onclick = multiples(fix);
HTML:
<label for="value">Enter Value: </label>
<input id="value1" class="value1" type="number" title="value field" placeholder="e.g. 1000">
<button type="button" id="solution1_btn" title="solution 1 button">Enter</button>
<input id="result1" class="result1" type="number" disabled>

Gosh, there is quite a few problems with your code, I'll try to run through them all.
Referencing HTML elements
HTML elements can be referenced in many ways, as you have discovered. Generally, you should pick the most appropriate and stick with it. If you use an id and a class things get confusing quickly - espcially seeing as id's should be unique, but classes need not necessarily be so. In your case, I think you're safest to stick with id, and then always use document.getElementById.
Multiple boolean checks
Regarding this line of code
if (i % 3 || i % 5 === 0) {
You probably expect that that equates to "if i is divisible by 3 or 5", and that is a logical (and often misunderstood) part of boolean logic. In actual fact, you should think "if i is divisible by 3 or i is divisible by 5", which equates to the following in code
if ((i % 3) === 0 || (i % 5) === 0) {
Yes, unfortunately you need to repeat the === 0 part twice.
Variable scope
This one's a big subject, and there is plenty of other information on the subject, but suffice it to say that in your function newSum is defined only inside an if block, and is redefined every iteration of your loop, so it wont contain the sum as you may be expecting.
In any case, it's uneccessary, you should just return sum
function multiples(num) {
// declare sum assign it value 0
var sum = 0;
// declare a for loop that iterates while the counter "i" is less than num
for (var i = 0; i < num; i++) {
// if statement test whether the division remainder of 3 and 5 are equal to 0
if ((i % 3) === 0 || (i % 5) === 0) {
// assigns the value of i to sum
sum += i;
};
};
// returns the value of sum from the function callback argument 1000 etc.
return sum;
};
Event handlers
You are trying to set an event to occur onclick with this code
solution1.onclick = multiples(fix);
This attempts to add an event handler with the result of calling multiples - not multiples itself. You should assign the event handler a function, and assign the value of the field to the result of calling the multiples function.
solution1.onclick = function(){
result1.value = multiples(parseInt(value1.value,10));
};
Working example
Below is a working example of your code, hopefully helps you pull this all together.
var solution1 = document.getElementById("solution1_btn");
var value1 = document.getElementById("value1");
var result1 = document.getElementById("result1");
function multiples(num) {
// declare sum assign it value 0
var sum = 0;
// declare a for loop that iterates while the counter "i" is less than num
for (var i = 0; i < num; i++) {
// if statement test whether the division remainder of 3 and 5 are equal to 0
if ((i % 3) === 0 || (i % 5) === 0) {
// assigns the value of i to sum
sum += i;
};
};
// returns the value of sum from the function callback argument 1000 etc.
return sum;
};
solution1.onclick = function(){
result1.value = multiples(parseInt(value1.value,10));
}
<label for="value">Enter Value: </label>
<input id="value1" class="value1" type="number" title="value field" placeholder="e.g. 1000">
<button type="button" id="solution1_btn" title="solution 1 button">Enter</button>
<input id="result1" class="result1" type="number" disabled>

Here is a fiddle with you problem - I hope solved: http://jsfiddle.net/w0qvdqb2/
There are few different problems in your code, first:
solution1.onclick = multiples(fix);
this means that multiples method should execute and return value is assigned to variable solution1.onclick but solution1.onclick accept callback.
Than based on your comments condition hasn't beed written as it's described.
And mixing with inputs and outputs classes and ids.
Please review updated code.

Related

Having trouble with a Javascript adding system (simple but I'm slow)

So I am trying to make a program here where I press a button and once its pressed I input a number (from 1-3) and then it outputs the inputted value.
Then you can press the button again and add another value (again from 1-3) and it adds the second input to the first input and so on.
This is the code I've got so far and it doesn't work, it just outputs my inputted value and that's it. Nothing gets added and updated.
<script type="text/javascript">
function addone()
{
x=parseInt(prompt("What goal importance did you complete?"));
var sum = 0;
if (x === 1)
{
sum = sum + x;
}
else if (x=== 2)
{
sum = sum + x;
}
else if (x=== 3)
{
sum = sum + x;
}
document.getElementById("myBtn").innerHTML = x;
}
</script>
The button and the ouput are with:
<button onclick="addone()">Coins</button>
<h1>Coins:</h1>
<h4 id='myBtn'>0</h4>
As pointed out by #Aplet123, each time you execute the addOne function, you restart the sum as 0.
The simplest way is to initialize it outside the function.
By the way, there is no need for the elseif conditions in your code, regarding the feature you want to achieve, the best, for readability should be to use a AND condition :
<script type="text/javascript">
var sum = 0;
function addone()
{
x=parseInt(prompt("What goal importance did you complete?"));
if (x >= 1 && x <=3)
{
sum = sum + x;
}
document.getElementById("myBtn").innerHTML = sum;
}
</script>
You have to fix one thing before moving on. You are instantiating the sum as 0 whenever you run the function. To fix this, declare the sum outside of the function. You can reset it if you want later in the program if you like.
Next, you want to accept only 1, 2 or 3 as the input. You can shorten the if else condition so that it checks that input is more than or equal to 1, but less than or equal to 3.
Finally - You are adding the values of input to the sum variable. The variable x is not changing itself. So, you will always see the number you input. Change the innerhtml value to sum.
EDIT - I have also included comments in the code below -
var sum = 0; //Declare sum outside the function
function addone(){
let x=parseInt(prompt("What goal importance did you complete?"));
if (x >= 1 && x <=3){ //Shorten the if else condition
sum += x;
}
document.getElementById("myBtn").innerHTML = sum; //Display the sum
}

How to iterate through possible null values in javascript without errors

I have up to 100 inputs on my screen, each one has either a numerical value, or is null (as its not been loaded onto the screen yet), I want to be able to take the value's of each of these inputs, and add them together to get a final value.
I have attempted this with a for loop, iterating through them, but once it gets to the null value ones, it returns 'NaN' error.
The first input is called 'Input1', the second 'Input2' etc...
My code below:
var val = 0; //assigning the final value OUTSIDE the for loop to stop it assigning itself as 0 every loop
for (var calc = 0; calc < 100; calc++) //less than 100 as of 100 inputs
{
var inputVal = $('#Input'+calc).val(); //grabbing each input on screen
var floatVal = parseFloat(inputVal); // converting each value to float
var finalVal = finalValue + floatVal; //takes the val of 0, and adds each input value onto it per loop
}
alert(finalVal);
This always returns 'NaN'.
If I set the for loop to 'calc < 2' for example, and load 2 inputs on the screen, it will work, so I'm assuming its because the other values are null?
Thank you
You can use the Number.isNaN(value) function to skip to the next loop iteration if the value is NaN.
Noticed in your code you declare val but then never use it, instead you declare a new finalVal on every loop. You should declare finalVal before the loop and add to it on every iteration, as such:
var finalVal = 0;
for (var i = 0; i < 100; i++)
{
var inputVal = $('#Input'+i).val();
var floatVal = parseFloat(inputVal);
if (Number.isNaN(floatVal))
{
continue;
}
finalVal += floatVal;
}
alert(finalVal);

How does Javascript variable works?

Recently started learning Javascript.
Given an assignment for my class, to click a button (a number 10 is written on the button), and there has to be "Result = 55". (here all numbers from 0 to 10 are added)
To change words by clicking buttons, wrote code like this:
function myFunction(num) {
var p = document.getElementById("mydata");
for (var i = 0; i <= num; i++) {
sum = sum + i;
p.innerHTML = "Result = " + sum;
}
}
After submitting assignment for school, learned that had to add var sum = 0 above var p = document.getElementById("mydata")
However, do not understand what var sum = 0 means. As for looks already show when to begin and end calculating, feel like it doesn't have to be there.
var sum = 0; declares a local variable named sum, and sets its initial value to 0.
If you don't do this, when you do:
sum = sum + i;
the variable sum is initially undefined, and adding i to it results in NaN (Not a Number).
Some languages (e.g. PHP) automatically treat initialized variables as 0 in arithmetic expressions, but JavaScript doesn't do this, so you need to specify the initial value of the variable.
This has nothing to do with the way the for loop determines when to begin and end. It's about how to correctly add the numbers along the way.
It doesn't have to be before the p assignment, but it needs to be before the for loop.
Also, the line
p.innerHTML = "Result = " + sum;
doesn't need to be inside the loop. You should wait until the loop is done.

Javascript pairwise comparison for difference between 6 variables

In javascript I am trying to automate the pairwise comparison of up to 6 integers in input boxes, comparing numbers as they are entered until 3 numbers are within 0.2 of one another. It is not necessary to enter all 6 values in order to have three numbers within 0.2 of one another, therefore some of the 6 potential input values may remain null or 0, but which should be ignored in the comparisons.
I have loaded the variables into a function i.e. var fev1 = document.getElementById('fevOne').value, but am not sure how to go about comparing each against one another apart from writing out every single possible case..
Does anyone have any idea how I should approach this?
My very sparse example code is below....
<head>
function reproduce() {
var fev1 = document.getElementById('fevOne').value;
var fev2 = document.getElementById('fevTwo').value;
var fev3 = document.getElementById('fevThree').value;
var fev4 = document.getElementById('fevFour').value;
var fev5 = document.getElementById('fevFive').value;
var fev6 = document.getElementById('fevSix').value;
//essentially, I don't know where to begin in building this formula, but imagine that I would need to use a loop
}
</head>
<body>
<input type="text" name="fevOne" id="fevOne" value="">
<input type="text" name="fevTwo" id="fevTwo" value="">
<input type="text" name="fevThree" id="fevThree" value="">
<input type="text" name="fevFour" id="fevFour" value="">
<input type="text" name="fevFive" id="fevFive" value="">
<input type="text" name="fevSix" id="fevSix" value="">
</body>
For a bit of background, I am building a medical form which will identify whether the lung function measurements (forced expiratory volume in 1 second, FEV1, measured in Litres) were collected with sufficient reproducibility (ie. 3 within 0.2L of one another), with the intent that the highest of these 3 values is taken as the clinically relevant value, stored for the patient.
Thanks in advance for any help!
Rory
Quick and dirty: https://jsfiddle.net/8081wucv/2/
function check() {
var text = document.getElementById('check');
Declare the function and get the element where I will put the bit of text
var values = [];
for (var i = 0; i < 6; i++) {
var value = document.getElementById('fev' + i).value;
if (/\d+\.?\d*/.test(value)) {
values.push(value);
}
}
Initialise the array and loop over the elements. If they're just digits with an optional point then push it onto the array
values.sort();
var passing = false;
Sort the array so we can do the next check easily and initialise the boolean that says whether or not the test passed.
for (var x = 0; x < values.length; x++) {
if (values[x + 2] - values[x] <= 0.2) {
passing = true;
break;
}
}
Loop over the array. If there are 3 elements (2 elements ahead, in the sorted array, minus this element) that have a difference of 0.2 or less then the test passes.
if (passing) {
text.innerHTML = 'passing';
} else {
text.innerHTML = 'not passing';
}
}
Update the text.
You can remove the final block and change it to return passing; if you just want a function.
The general idea would be check all inputs anytime a change is made to one of them using a nested loop structure that compares all combinations of inputs. It has to be bullet proof for clinical use and allow technicians to change their minds and erase, alter and correct values. Note that if the spirometry tests have been completed and all results are entered, this example reports the maximum clinical fev identified, not the one that minimizes the difference between two test results.
Note the HTML of this example identifies each input using a zero based "data-index" attribute, not "id" property. The "fevSetup" function would normally be called after the window load event has fired while running the snippet calls it directly. The maximum difference was increased slightly because JavaScript
decimal arithmetic is not always exact ( I haven't stored the text input by the technician which might be better for reporting purposes).
function fevSetup() {
var MAX_DIFF = 0.2000001;
var values = [];
var i,j;
var fevInputs = document.querySelectorAll('[data-type=fev]');
for( i = 0; i < fevInputs.length; ++i) {
fevInputs[i].addEventListener("change", checkFev);
}
function checkFev() {
var thisFev = Number( this.value);
var index = Number(this.dataset.index);
if(isNaN( thisFev) || thisFev <= 0) {
console.log("Invalid input: " + this.value)
this.value = "";
thisFev = undefined;
}
values[ index] = thisFev // may erase a previous entry
var clinicalFevs = [];
for( var i = 0; i < values.length-1; ++i) {
for( var j = i+1; j < values.length; ++j) {
if( values[i] && values [j]
&& (Math.abs( values[j] - values[i]) <= MAX_DIFF)) {
clinicalFevs.push( Math.max (values[i], values[j]));
}
}
}
if( clinicalFevs.length) {
var clinicalFev = Math.max.apply(Math, clinicalFevs);
console.log("Clinical Fev: %s", clinicalFev);
}
}
}
// window.addEventListent("load", fevSetup);
fevSetup(); // for testing
<input type="text" data-type="fev" data-index="0" value="">
<input type="text" data-type="fev" data-index="1" value="">
<input type="text" data-type="fev" data-index="2" value="">
<input type="text" data-type="fev" data-index="3" value="">
<input type="text" data-type="fev" data-index="4" value="">
<input type="text" data-type="fev" data-index="5" value="">
Naturally this code is supplied as is, without any form of guarantee or statement of fitness for purpose. I hope, however, it provides you with something to go on.
Not sure about this, but what about comparing Min and recurse ?
var inp = document.querySelectorAll('input'), // Jack's solution is more elegant.
fevArray = [];
[].forEach.call(inp, (e) => {
if (e.value) {
fevArray.push(parseFloat(e.value,10));
}
});
var recursiveCheck = function(arr){
if (arr.length >= 3) {
// If Max and min difference is not in the interval, change max with the second greatest value and recurse.
if ((Math.max.apply(null, arr) - Math.min.apply(null, arr) <= 0.2)) {
return arr;
}
recursiveCheck(arr.splice(arr.indexOf(Math.max.apply(null, arr)),1));
}
}
console.log("result", recursiveCheck(fevArray)); // should return undefined if not meeting conditions, or the array otherwise.

Is it Possiable to call to previous increments of a variable?

for example lets say i have a loop that is doing basic counting, while the variable is less than 16 the loop will run and at the end of the loop you add 2 to the variable and add one to a "count" variable
what i want to know is if its possible to callback to any of the previous variables for either variable for example can i count all the times count % 2 === 0?
im not quite sure if once a variable makes any kind of change if all previous versions of that variable are gone
http://codepen.io/anon/pen/Gojoxm
var two = 0;
var count = 0;
while ( two < 16) {
two += 2;
count++;
};
console.log(count);
If I understand you right, then no, you cannot. When you assign a new value to a variable, the previous value is lost.
You have to either run this loop again or store intermediate values in an array:
var values = [];
var two = 0;
while (two < 16) {
two += 2;
values.push(two);
}
console.log(values.length); // the same result
Then, you will always be able to do whatever you want with these values.
For example, you can check if there were any odd values:
var anyOddNumbers = values.some(function(x) { return x % 2 === 1; }); // false

Categories