How to auto sum dynamic input fields in javascript - javascript

I'm trying to make an auto sum.
I'm starting with a text input field and a button. Pushing the button ads a new input field. Sum field should get ... the sum.
I have troubles adding the values in javascipt.
Thanks!
var counter = 1;
sum.value= number0.value;
function addNumber(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "<input type='text' name='number" + counter + "'>";
document.getElementById(divName).appendChild(newdiv);
sum.value += document.getElementById("number' + counter + '").value;
nr++;
}
...
<div id="field"> Add value: <input type="button" value="add" onClick="addNumber('total');"><br>
<div id="total"><input type="text" name="number0"></div>
<input type="text" name="sum" id="sum">

I think this is what you are trying to do:
var counter = 1;
function addNumber(divName){
var sum = document.getElementById('sum');
var newdiv = document.createElement('div');
newdiv.innerHTML = "<input type='text' name='number" + counter + "'>";
document.getElementById(divName).appendChild(newdiv);
sum.value = getSum(counter);
counter++;
}
function getSum(numberOfDivs) {
var sum = 0;
for (var i=0 ; i<numberOfDivs; i++) {
sum += parseInt(document.getElementsByName('number' + i)[0].value);
}
return sum;
}
Check this plunk: http://plnkr.co/edit/5UE6YyDWmaHq5ZvVY542

Note: Explanation of the code is after the snippet.
Here's a rewrite of your code that accounts for NaN results and updates as the fields are changed (not only when the "Add" button is clicked). It also dynamically generates the first field, too. ;)
window.onload = function() {
var counter = 0, sum = document.getElementById('sum');
document.getElementById('add').addEventListener('click', function() {
counter += addNumber(counter, sum);
});
counter += addNumber(counter, sum);
};
function addNumber(counter, sum) {
calculateSum(sum);
var newdiv = document.createElement('div');
newdiv.innerHTML = '<input type="text" name="number' + counter + '" class="number" />';
newdiv.addEventListener('keyup', function() {
calculateSum(sum);
});
sum.parentNode.insertBefore(newdiv, sum);
return 1;
}
function calculateSum(sum) {
sum.value = 0;
var divs = document.getElementsByClassName('number');
for(var i = 0; i < divs.length; i++) {
sum.value = (isNaN(parseInt(sum.value)) ? 0 : parseInt(sum.value)) + (isNaN(parseInt(divs[i].value)) ? 0 : parseInt(divs[i].value));
}
}
<div id="field">
Add value: <input type="button" value="add" id="add" />
<br />
<input type="text" name="sum" id="sum" />
</div>
It's pure JavaScript and is set-up to run without needing to call the functions from within the HTML.
Simply put, I separated the addNumber() into two functions. One to add a new field and the other to determine the total sum.
The addNumber() adds a new number field, applies an EventListener to the added fields to execute the calculatSum() whenever the browser recognizes a keyup event, and returns a value of 1 which is then added to the counter variable.
The calculateSum() zeros the sum and recalculates using the .number I added to the generated input fields. It is NaN-safe. Basically, this means the values that are ran through parseInt() are then checked that they are numbers. If parseInt() fails, it reports the value as Not a Number, or NaN. The function forces it to report a value of 0 instead of NaN.
To top it off, the script starts by defining the counter variable as 0, adding an EventListener for whenever the "Add" button gets clicked, and executes the addNumber() to place the first number field.

Related

how to print based on value entered

so If I entered 10, number 10 should be printed ten times
function function_name(number) {
for (var counter = 1; counter <= number; counter++) {
document.write("the number is" + number);
}
}
<label for="number">Enter number: </label>
<input name="number" id="number" />
Looks like you just need to:
Add a button to your HTML
Add a click handler to your button that will activate your function
function writeTimes(number) {
for (var counter = 1; counter <= number; counter++) {
document.write("the number is" + number);
}
}
function doTheThing() {
var input = document.getElementById("my-input"); //get the input element
var numberOfTimes = input.value; //get the number of times
writeTimes( numberOfTimes ); //call your function
}
<label for="number">Enter number: </label>
<input id="my-input" name="number" id="number" />
<button onclick="doTheThing()">Go</button>
// This function *does* something. Give it a name that reflects it's behavior.
// You can always rename it later if you change what it does.
//
function spamNumber(number) {
// Use let instead of var, it's replacement for var with less wtf behavior
//
for (let counter = 1; counter <= number; counter++) {
// I don't care for document.write. It's totally unusable in production code.
// But sure, why not? At least add a line break so the outputs
// don't smush together.
//
document.write("the number is " + number + '<br/>');
}
}
// Find the input element so we can add a listener
//
document.querySelector('input')
// Listening in this case only to keydowns that occur while input has focus.
//
.addEventListener('keydown', function onKeydown(evt) {
if (event.key === 'Enter') {
// evt.target is the input element, number in it's value property.
// Force value to integer in case someone inputs garbage. We can
// fail silently and move on.
//
spamNumber( parseInt(evt.target.value) || 0)
}
})
// Now type in your number and press Enter
<label for="number">Enter number: </label>
<input name="number" id="number" />
From your question and comments , i think you are looking for this:
onload = function (){
var result = document.getElementById('result');
var number = document.getElementById('number');
number.oninput = function (){
if(number.value == "0" || number.value.length == ""){result.innerHTML="";}else{}
var counter = "";
var repeat =number.value;
while (repeat > 0) {
repeat--;
var str =" (the number is " + parseInt(number.value)+" )";
result.innerHTML= str.repeat(number.value);
}
return counter;
number.onpropertychange = number.oninput;
number.onchange = number.oninput;
}};
<label for="number">Enter number: </label>
<input name="number" id="number" /><br />
<span id=result></span>

Taking the sum of user inputs and storing it as a variable

What is the best way to calculate sum of user inputs from an array and then store that value as a variable?
I have a function here that creates an array from user inputs(number4[]).
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Asset($) " + (counter + 1) + " <br><input type='text' name='number4[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
<div class="container7">
<div id ="dynamicInput">
Assets 1($): <INPUT type="text" name="number4[]">
</div>
Liabilities 1(%): <INPUT type="text" name="number5">
Result($): <INPUT type="text" name="total1">
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Calculate"onclick="javascript:networth()">
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Add asset fields"onclick="addInput('dynamicInput');">
</div>
</FORM>
I have no code for total1 yet. so basically i have the array i just need help identifying the sum and then assigning it as a variable.
document.getElementsByName("number4[]") will return an array of the elements you need to total up
function networth(){
var totNo = document.getElementsByName("number4[]").length;
var sum = 0;
for(var i=0; i<totNo; i++){
sum += parseInt(document.getElementsByName("number4[]")[i].value);
console.log(sum);
}
}
Add an id to your input elements and use
var val1 = document.getElementById("the id of the input you want").value
//repete for val2... with a different id and add the val variables
You need to get all the input elements you want to sum. You can use the querySelectorAll to get all the elements with a same CSS selector common in all the inputs you want to sum.
https://www.w3schools.com/jsref/met_document_queryselectorall.asp
Finally you can get the input in the same way with querySelector, as is only one there is no need to use the All variation.
https://www.w3schools.com/jsref/met_document_queryselector.asp
var counter = 1;
var limit = 3;
function networth(){
var inputs = document.querySelectorAll("form #dynamicInput input");
var networth = 0;
for (var i = 0; i < inputs.length; i++) {
networth += parseFloat(inputs[i].value);
}
document.querySelector("input[name=total1]").value=networth;
}
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Asset($) " + (counter + 1) +
" <br><input type='text' name='number4[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
<form>
<div class="container7">
<div id="dynamicInput">
Assets 1($):<br>
<INPUT type="text" name="number4[]">
</div>
Liabilities 1(%):
<INPUT type="text" name="number5"> Result($):
<INPUT type="text" name="total1">
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Calculate" onclick="javascript:networth()" />
<INPUT type="button" style="background-color:#FF8800; border-color:BLACK;" value="Add asset fields" onclick="addInput('dynamicInput');" />
</div>
</FORM>

How to store inputs from a textbox in array in Javascript

<!DOCTYPE html>
<html>
<head>
<form id="form1">
Beets:<input id="number1" type="integer" size = "5">
Artichokes: <input id="number2" type="integer" size = "5">
Carrots: <input id="number3" type="integer" size = "5">
</form>
<button id = "submitButton" onclick="RunApp()" > Submit</button>
<button id = "displayButton" onclick="getAllValues()" > Display</button>
<script>
var str = "";
function getAllValues() {
var input1, inputs;
input1 = document.getElementById("form1");
inputs = input1.elements["number1"].value;
for (i = 0; i < inputs.length; i++) {
str += inputs[i].value + " ";
}
alert(str);
}
function RunApp()
{
var beets, artichokes, carrots, input1, input2, input3;
// getting inputs into variables
input1 = document.getElementById("form1");
beets = input1.elements["number1"].value;
input2 = document.getElementById("form1");
artichokes = input1.elements["number2"].value;
input3 = document.getElementById("form1");
carrots = input1.elements["number3"].value;
if (beets == "" || carrots == "" || artichokes == "" || isNaN(beets) || isNaN(carrots) || isNaN(artichokes))
{
document.getElementById("demo").innerHTML+= "not valid" + "<br>";
document.getElementById("demo").innerHTML+= "--------------------------" + "<br>";
}
else
{
document.getElementById("demo").innerHTML+= "Beets = " + beets + "<br>"; document.getElementById("demo").innerHTML+= "Artichokes = " + artichokes + "<br>";
document.getElementById("demo").innerHTML+= "Carrots = " + carrots + "<br>";
}
}
</script>
<p id="demo"></p>
</head>
<body>
</body>
</html>
First, this is my first time learning JS.
So, I have a text-box, a submit button, and a display button. When I enter a number in the text-box, and click submit, it shows the number. I enter my second number and clicking the submit button shows me the second number. Then I click on the display button, it will shows the number 1 and number 2 in order. If I have more inputs in the text-box, the display button will show the entire list of all the inputs from the array.
Thank you!
Well, since it's your first time and you're learning I won't just give you the answer, but I'll point you in the right direction.
You want to attach a click event on the submit button to add the value to an array, and then print the array on click of the display button.
i think first you must google for this. I write something and you can improve this. I only want to give an example.
HTML:
<input type="text" id="inputbox">
<br/>
<button type="button" id="submit">Submit</button>
<button type="button" id="display">Display</button>
<br/>
<div id="screen"></div>
JS:
var inputArray = [];
var input = document.getElementById('inputbox');
var screen = document.getElementById('screen');
document.getElementById('submit').onclick = function () {
inputArray.push(input.value);
screen.innerHTML = input.value;
};
document.getElementById('display').onclick = function () {
screen.innerHTML = inputArray
};
http://jsfiddle.net/y9wL27y0/

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

Javascript getting the values of an array of input boxes

I have an input field that has a button to dynamically add another input field and I am trying to get it so that when I click plot i am able to grab the content inside the input fields gps[]
html
<div id="marker">
<input type="text" name="gps[]" id="gps">
<input type="text" name="gps[]">
</div>
Plot
javascript
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<input type='text' name='gps[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
$('body').on('click','.plot', function(){
var y = $('input[name="gps[]"]').val();
console.log(y);
});
You have to use .map to get the value of all the elements in the collection :
var y = $('input[name="gps[]"]').map(function() {return this.value;}).get();
FIDDLE

Categories

Resources