The specified value "." cannot be parsed, or is out of range - javascript

I trying to make a calculator but I have the problem with the "dot" because give me advertisement like this...
"The specified value "." cannot be parsed, or is out of range."
This is my code...
numberDot.addEventListener('click', function() {
numberDot = '.' ;
input.value = input.value + numberDot;
console.log(typeof(input.value));
console.log(input.value);
});

This is one way to do it
Use type="number" inputs and radio buttons to choose the operation. That helps the person to enter numbers. You can also use type="text"
The important part is the conversion from string data into numeric values
When you read data from the value property of an input, the data is returned as a string. It can be converted to a number using parseInt (for integers) or parseFloat (for floating point). If it can't be parsed, NaN (Not a Number) is returned. To test for NaN, use isNaN().
For example:
let x = "kittens";
let n = parseInt(x);
if (isNaN(n)) {
console.log(x + " is not a number");
}
The important part of this example is the conversion of numbers and figuring out which operation to perform.
// get the elements in the DOM
let numberOne = document.getElementById("numberOne");
let numberTwo = document.getElementById("numberTwo");
let output = document.getElementById("output");
let calculator = document.getElementById("calculator");
// every time the calculator values change
calculator.addEventListener('change', function(evt) {
// get the values from the number inputs and try to convert them to floating point
let valueOne = parseFloat(numberOne.value);
let valueTwo = parseFloat(numberTwo.value);
// if both numbers are numbers (this is not 100% accurate)
if (!isNaN(valueOne) && !isNaN(valueTwo)) {
// create a variable to store the result
let value = 0;
// get the radio buttons
let ops = calculator['operation'];
// use the selected radio button to determine the operation
switch (ops.value) {
case '+':
value = valueOne + valueTwo;
break;
case '-':
value = valueOne - valueTwo;
}
// display the result
output.textContent = value;
}
});
<form id="calculator">
<!-- first number -->
<input id="numberOne" type="number" placeholder="1.0" step="0.01" min="0" max="10">
<br>
<!-- radio buttons for operations -->
<label for="add">Add
<input type="radio" name="operation" value="+">
</label>
<label for="subtract">Subtract
<input type="radio" name="operation" value="-">
</label>
<br>
<!-- second number -->
<input id="numberTwo" type="number" placeholder="1.0" step="0.01" min="0" max="10">
</form>
<!-- to display the result -->
<output id="output"></output>

For those who still end up here with the above error from the browser. Generally, you will get this error when inserting the string into the input field of the type number. Check the Input field type attribute. This should do the trick.

Related

Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>

How can I access these form values?

I want to create a form where I will perform an operation with the values entered by the user, but when the function runs, I get NaN return. Thank you in advance for the help.
function test() {
var age = document.getElementsByName("person_age").value;
var weight = document.getElementsByName("person_weight").value;
var size = document.getElementsByName("person_size").value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>`
Output:
NaN
When I get the values from the user and run the function, I get NaN feedback. how can i solve this problem.
There are multiple errors that you have to correct
1) When you use getElementsByName, It will return NodeList array like collection. So you have to get the element by using index as:
var age = document.getElementsByName( "person_age" )[0].value;
2) If you need sum of all three value then you have to convert it into Number type because document.getElementsByName( "person_age" )[0] give you value in String type. So you can do as:
+document.getElementsByName( "person_age" )[0].value
function test() {
var age = +document.getElementsByName("person_age")[0].value;
var size = +document.getElementsByName("person_size")[0].value;
var weight = +document.getElementsByName("person_weight")[0].value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
Just a Suggestion: You can use Document.getElementById if you want to directly access the value. Just add an ID property in your element. It will return a string value, convert that to int and you're good to go.
function test() {
var age = document.getElementById("person_age").value;
var weight = document.getElementById("person_weight").value;
var size = document.getElementById("person_size").value;
document.getElementById("result").innerHTML = parseInt(weight) + parseInt(size) + parseInt(age);
}
<form>
<input type="text" name="person_age" id="person_age">
<input type="text" name="person_size" id="person_size">
<input type="text" name="person_weight" id="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
getElementsByName will always return an array-like nodelist so, if you were to use it you would need to access the first index [0]. Instead add a class to each input and use querySelector to target it.
The value of an input will always be a string (even if the input is type "number"), so you need to coerce it to a number, either by using Number or by prefixing the value with +.
So, in this example I've updated the HTML a little by adding classes to the inputs, and changing their type to "number", and removing the inline JS, and updated the JS so that the elements are cached outside of the function, an event listener is added to the button, and the values are correctly calculated.
// Cache all the elements using querySelector to target
// the classes, and add an event listener to the button
// that calls the function when it's clicked
const ageEl = document.querySelector('.age');
const weightEl = document.querySelector('.weight');
const sizeEl = document.querySelector('.size');
const result = document.querySelector('#result');
const button = document.querySelector('button');
button.addEventListener('click', test, false);
function test() {
// Coerce all the element values to numbers, and
// then display the result
const age = Number(ageEl.value);
const weight = Number(weightEl.value);
const size = Number(sizeEl.value);
// Use textContent rather than innerHTML
result.textContent = weight + size + age;
}
<form>
<input type="number" name="age" class="age" />
<input type="number" name="size" class="size" />
<input type="number" name="weight" class="weight" />
<button type="button">Calculate</button>
</form>
<h3 id="result"></h3>`

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

Limit input to show only thousans in HTML or JS

I have an input filed where the user can enter some numbers. I want to limit the user to enter only thousands.
.
on the image, the user can enter other numbers even if the step is 1000.
onblur is executed when you lose the focus, so try this :
function autoThousand(){
var input = document.getElementById('thousand');
if (input.value%1000 !== 0 ){
input.value-=input.value%1000;
}
}
<input type="number" id="thousand" onblur="autoThousand();" step="1000">
This will round all number inputs to multiples of their step value, when they lose focus. It uses traditional rounding, where it rounds 1499 down to 1000 and 1500 up to 2000. (You can remove the commented line of code to always round down.)
This is one of those "add it and forget it" bits of code, where you just need to add inputs of type number, with a limit, and it will automatically round them all for you.
document.querySelectorAll("input[type=number][limit]").forEach(function(input) {
input.addEventListener("change", function() {
var value = parseInt(this.value, 10);
var limit = parseInt(this.getAttribute("limit"), 10);
value = value + (limit / 2); // remove this to always round down
this.value = value - (value % limit);
});
});
<input type="number" limit="1000" />(multiples of 1000)<br />
<input type="number" limit="100" />(multiples of 100)<br />
<input type="number" limit="500" />(multiples of 500)<br />
use this,
if you still want to make the field number field set the type="number" , step="1000", min="1000" max="any value of your choice"
<input type="text" name="quantity" id="num" onchange="checkInput()">
<script>
function checkInput(){
get_num = new Number(document.getElementById('num').value)
if(get_num < 1000){
document.getElementById('num').value = ""
alert("You must enter number in thousands")
}
}
</script>
Set 'max', 'min' and 'step' value.
<input type="number" name="points" step="1000" max="100000" min="1000">

add and get the average of values inputted by user from dynamic textboxes using javascript

I have 5 textboxes displayed, a user can add more textboxes dynamically. However, I am not able to get the the sum and average of the values inputted by users on those textboxes. Can you please help me. I will really appreciate it.
Hear is the HTML code:
<html>
<head>
<title> Grading System </title>
</head>
<script src="addInput.js" language="Javascript" type="text/javascript">
</script>
<body>
<center> GRADING SYSTEM <br><br>
<form method="POST">
<div id="dynamicInput">
Subject number 1<br><input type="text" name="myInputs[]"><br>
Subject number 2<br><input type="text" name="myInputs[]"><br>
Subject number 3<br><input type="text" name="myInputs[]"><br>
Subject number 4<br><input type="text" name="myInputs[]"><br>
Subject number 5<br><input type="text" name="myInputs[]">
</div>
<input type="button" value="Add a subject" onClick="addInput('dynamicInput');">
<input type="button" name="BtnCompute" onClick="avg('dynamicInput');" value="Compute Average">
</form>
</body>
</html>
Then here's the Javascript code:
var counter = 5;
var limit = 10;
var sum=0;
var average=0;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Subject number " + (counter + 1) + " <br><input type='text' name='myInputs[]' >";
document.getElementById(divName).appendChild(newdiv);
counter++
}
}
function avg(divName){
sum += document.getElementsByName("myInputs[]")[0].value;
average = sum / counter
alert("Average is " + average);
return false;
}
The problems with your original function:
function avg(divName) {
// you only look at one <input> element ever time, rather
// than iterating over the collection returned by
// 'document.getElementsByName("myInputs[]")'; plus you're using
// a global value which is (at least potentially) exposed to
// every other function, which makes it vulnerable to being
// over-written by other values; also: you're not ensuring that
// the entered-value is a Number (an <input> returns its value as
// a String, not a Number):
sum += document.getElementsByName("myInputs[]")[0].value;
// here you're working out the average of two global values,
// both of which could be corrupted by other functions, and
// neither of which - being global - are guaranteed to be
// Numbers, since you're not enforcing that anywhere. Also
// you've exposed yourself to potential browser interference
// by not ending the line with the (optional) semi-colon:
average = sum / counter
// this is personal, but for debugging I'd recommend use of
// console.log() (but, again, a purely personal reccomendation
// and not really a 'problem' as such):
alert("Average is " + average);
return false;
}
My correction of your original function would be:
function avg() {
// rather than passing in an argument explicitly, I've opted
// to use a custom data-* attribute to contain the id of the
// relevant <div> (see the HTML below, this simplifies
// changes somewhat in the future):
var div = document.getElementById(this.dataset.divname),
// using Node.querySelectorAll() to retrieve the relevant
// <input> elements (my inclination would be to further
// amend the selector to 'input,' but that depends on
// whether or not you'd have any irrelevant <input>
// elements contained within the same <div>):
inputs = div.querySelectorAll('input[type=text][name="myInputs[]"]'),
// using Function.prototype.call() to apply the
// Array.prototoype.map() function to the Array-like
// NodeList returned by document.querySelectorAll(),
// and returns an Array of (in this case) entered values:
sum = Array.prototype.map.call(inputs, function (inputNode) {
// here we convert the existing value of the <input>
// element-node to a Number (<input> elements return
// their values as a String) or, if the value can't
// be converted to a Number, or the <input> has no
// entered value, we return 0:
return parseFloat(inputNode.value) || 0;
// using Array.prototype.reduce() to sum the
// Array of values returned by Array.prototype.map():
}).reduce(function (a, b) {
// here we return the sum of the previous number
// and the current number:
return a + b;
// the 0 here is the initial starting value
// to which the numbers are added:
}, 0),
// ensuring that the counter variable (first
// argument) is parsed into an integer value
// (using parseInt(), in base-10 (the second
// argument):
average = sum / parseInt(counter, 10);
console.log("Average is " + average);
return false;
}
// here we use JavaScript to attach the event-handling function to
// the relevant <input> (I added the 'id' to enable this), and
// this binds the avg() function to handle the 'click' event:
document.getElementById('btnCompute').addEventListener('click', avg);
The HTML for the amended <input> element:
<input id="btnCompute" data-divname="dynamicInput" type="button" name="BtnCompute" value="Compute Average" />
var counter = 5;
var limit = 10;
function addInput() {
// note that I've amended this function also, to
// use the 'data-divname' attribute to hold the
// 'id' of the relevant <div>:
var div = document.getElementById(this.dataset.divname);
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Subject number " + (counter + 1) + " <br><input type='text' name='myInputs[]' >";
div.appendChild(newdiv);
counter++
}
}
function avg() {
var div = document.getElementById(this.dataset.divname),
inputs = div.querySelectorAll('input[type=text][name="myInputs[]"]'),
sum = Array.prototype.map.call(inputs, function(inputNode) {
return parseFloat(inputNode.value) || 0;
}).reduce(function(a, b) {
return a + b;
}, 0),
average = sum / parseInt(counter, 10);
snippet.log("Average is " + average);
return false;
}
document.getElementById('addNew').addEventListener('click', addInput);
document.getElementById('btnCompute').addEventListener('click', avg);
label,
input[type=text] {
display: block;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<!--
Note that I've also amended your HTML, removing the
unnecessary <br /> elements, instead using CSS to
provide line-breaks; and also wrapping the <input>
elements in <labels>, both to enable the CSS line-
breaks and to enable clicks on the text to focus
the associated (nested) <input> element:
-->
<form method="POST" action="#">
<div id="dynamicInput">
<label>Subject number 1
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 2
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 3
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 4
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 5
<input type="text" name="myInputs[]" />
</label>
</div>
<input id="addNew" data-divname="dynamicInput" type="button" value="Add a subject" />
<input id="btnCompute" data-divname="dynamicInput" type="button" name="BtnCompute" value="Compute Average" />
External JS Fiddle demo, for experimentation/development.
Despite my correction of your function though, I'd probably take an alternative approach:
// because I retrieve the number of elements in a couple
// of places, I created a simple function to retrieve
// that number of elements:
function currentlyExisting(selector) {
return document.querySelectorAll(selector).length;
}
// rewritten in my own style (though this is irrelevant to the
// the question you asked):
function addNew() {
// still using the value of the custom 'data-divname'
// attribute:
var parent = document.getElementById(this.dataset.divname),
// rather than creating a HTML string, here I create nodes
// using document.createElement() and a textNode, using
// document.createTextNode():
label = document.createElement('label'),
input = document.createElement('input'),
// getting the number of currently-existing <input>
// elements using the above function, passing the
// selector as an argument:
current = currentlyExisting('input[name="myInputs[]"'),
limit = 10;
// if the current number of <input> elements is less than
// the limit:
if (current < limit) {
// we set the type of the created <input>:
input.type = 'text';
// and the name property:
input.name = 'myInputs[]';
// appending a textNode to the created <label> element:
label.appendChild(document.createTextNode('Subject number ' + (current + 1) + ':' ));
// appending the created <input> to the created <label>:
label.appendChild(input);
// attaching the created <label>, along with its own
// childNodes, to the parent div (retrieved and cached above):
parent.appendChild(label);
// setting the disabled property to true if the updated
// number of <input> elements is equal to, or greater than,
// the limit; or to false if the number of <input> elements
// remains less than the limit (preventing the addition of
// more <input> elements than that identified by the limit):
this.disabled = currentlyExisting('input[name="myInputs[]"') >= limit;
}
// all functions return a value, whether it's explicitly defined
// or undefined (as this one will), the return false of your
// original function can be added here instead if you prefer,
// but I - personally - feel it's unnecessary, so I left it out.
}
function average() {
// retrieving the relevant <div> element using the
// data-divname attribute once again:
var parent = document.getElementById(this.dataset.divname),
// retrieving the relevant <input> elements:
inputs = parent.querySelectorAll('input[name="myInputs[]"]'),
// creating an Array of the values of the relevant
// <input> elements, using Function.prototype.call()
// in order to use Array.prototype.map() on the
// Array-like NodeList returned by querySelectorAll():
values = Array.prototype.map.call(inputs, function (input) {
// returning the value of the current <input>
// element as a number to the array, using
// parseFloat() to convert that String to a
// Number; or returning 0 if the String cannot
// be parsed as a Number:
return parseFloat(input.value) || 0;
// using Array.prototype.reduce() to reduce the Array
// of numeric values (provided by map()) to a single
// number, the sum of the values:
}).reduce(function (a, b) {
// adding the previous and current values
// together:
return a + b;
// here the 0 is the initial value before the Array
// 'reduction' takes place:
}, 0),
average = sum / inputs.length;
// adding the values to the appropriate elements on screen
// for easier visualisation (and in a manner that persists):
document.getElementById('average').textContent = average;
document.getElementById('sum').textContent = sum;
document.getElementById('total').textContent = inputs.length;
}
// adding the click event handlers to the relevant button <input>
// elements using EventTarget.addEventListener():
document.getElementById('addNew').addEventListener('click', addNew);
document.getElementById('btnCompute').addEventListener('click', average);
function currentlyExisting(selector) {
return document.querySelectorAll(selector).length;
}
function addNew() {
var parent = document.getElementById(this.dataset.divname),
label = document.createElement('label'),
input = document.createElement('input'),
current = currentlyExisting('input[name="myInputs[]"'),
limit = 10;
if (current < limit) {
input.type = 'text';
input.name = 'myInputs[]';
label.appendChild(document.createTextNode('Subject number ' + (current + 1) + ':'));
label.appendChild(input);
parent.appendChild(label);
this.disabled = currentlyExisting('input[name="myInputs[]"') >= limit;
}
}
function average() {
var parent = document.getElementById('dynamicInput'),
inputs = parent.querySelectorAll('input[name="myInputs[]"]'),
sum = Array.prototype.map.call(inputs, function(input) {
return parseFloat(input.value) || 0;
}).reduce(function(a, b) {
return a + b;
}, 0),
average = sum / inputs.length;
document.getElementById('average').textContent = average;
document.getElementById('sum').textContent = sum;
document.getElementById('total').textContent = inputs.length;
}
document.getElementById('addNew').addEventListener('click', addNew);
document.getElementById('btnCompute').addEventListener('click', average);
label,
input[type=text] {
display: block;
}
#average::before {
content: 'Average: ';
}
#sum::before {
content: ', sum: ';
}
#total::before {
content: ', of: ';
}
#total::after {
content: ' entries.'
}
#total:empty::before,
#total:empty::after,
#sum:empty::before,
#average:empty::before {
content: '';
display: none;
}
<div id="results">
<span id="average"></span>
<span id="sum"></span>
<span id="total"></span>
</div>
<form method="POST" action="#">
<div id="dynamicInput">
<label>Subject number 1:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 2:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 3:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 4:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 5:
<input type="text" name="myInputs[]" />
</label>
</div>
<input id="addNew" data-divname="dynamicInput" type="button" value="Add a subject" />
<input id="btnCompute" data-divname="dynamicInput" type="button" name="BtnCompute" value="Compute Average" />
</form>
External JS Fiddle demo, for experimentation/development.
References
HTML:
Custom data-* attributes.
JavaScript:
Array.prototype.map().
Array.prototype.reduce().
document.getElementById().
document.getElementsByName().
document.querySelectorAll().
EventTarget.addEventListener().
Function.prototype.call().
HTMLElement.dataset.
parseFloat().
parseInt().
So I think you're missing a few things.
sum += document.getElementsByName("myInputs[]")[0].value;
this line gets only the first input field value, so you need a loop through all the input fields to get the actual sum
for (var i = 0; i < counter; i++)
sum += parseInt(document.getElementsByName("myInputs[]")[i].value);
Next, notice the addition of the parseInt(); method. This converts the input value (which javascript sees as a string by default) into an integer in which you can perform calculations on.
Hope that helps you, cheers

Categories

Resources