I want to have a webpage with one input box and two button. first button for adding input box value to my array and the second to sum all array values. but it return 0 :(
<input type="text" placeholder="Enter number" id="input">
<button id="add">Add to Array</button>
<button id="sum">Sum All</button>
<p id="text"></p>
<script>
var myArr = []; //contain numbers that i've inputed
var input = document.getElementById('input');
var addBtn = document.getElementById('add');
var sumBtn = document.getElementById('sum');
addBtn.onclick = function () {
myArr.push(input.value);
input.value = "";
}
function sumAll() {
var i , sum = 0;
for ( i in myArr.length ) {
sum += i;
}
return sum;
}
sumBtn.onclick = function(){
var paragraph = document.getElementById('text');
var a = sumAll();
paragraph.innerHTML = a;
}
</script>
You can use the for-of syntax to loop thru your array.
function sumAll() {
var i , sum = 0;
for ( i of myArr ) {
sum += Number(i);
}
return sum;
}
You need to run your for loop properly:
When you say for ( i in myArr.length ) {the value of i comes out as undefined so the summation never happens. You should use debugging to figure out such issues.
function sumAll() {
var i, sum = 0;
for (i = 0; i < myArr.length;i++) {
sum += +myArr[i];
}
return sum;
}
Notice +myArr[i];that uses unary operator +. This can attempt to convert the string in the input field to number(both int and floats).
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators
This should be way to go..
1.You have to use parseInt to treat values as ints
2.Loop correctly over array
<script>
var myArr = []; //contain numbers that i've inputed
var input = document.getElementById('input');
var addBtn = document.getElementById('add');
var sumBtn = document.getElementById('sum');
addBtn.onclick = function () {
myArr.push(input.value);
input.value = "";
}
function sumAll() {
var i , sum = 0;
for ( i in myArr ) {
sum += parseInt(myArr[i]);
}
return sum;
}
sumBtn.onclick = function(){
var paragraph = document.getElementById('text');
var a = sumAll();
paragraph.innerHTML = a;
}
</script>
Related
i'm trying to create a simple project where the user is prompted to enter how many numbers he would like to add(sum). then when he click the button, a javascript will create a number of input tags equal to the number he inserted and then he will fill them with a number and click another button to calculate the result of the summation and here is the problem. below is a simplified snippet explain what is the problem:
function CL(){
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type","text");
inpt.setAttribute("style","margin:5px;");
inpt.setAttribute("id","y"+i);
inpt.setAttribute("value","");
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
}
function Add(){
const y = 0;
const sum = 0;
var is;
for (var i = 1; i < 3; i++) {
is = i.toString();
y = Number(document.getElementById('y'+ is).value);
sum = sum + y;
}
document.getElementById("demo").innerHTML = sum;
}
in the for loop how can i use getElementById with variables id like item1,item2,item3,...,itemN??
is there other way to achieve what i want?
You can take all items with ID "y" + consecutive number prefix on this way document.getElementById('y' + i).value;
Do not use "Add" for function name and Functions do not have to start with capital letters!
calckStart();
function calckStart() {
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type", "text");
inpt.setAttribute("style", "margin:5px;");
inpt.setAttribute("id", "y" + i);
inpt.setAttribute("value", "");
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
var button = document.createElement('button');
button.innerHTML = 'ClickMe'
items.appendChild(button);
button.addEventListener('click', calculateVal);
}
function calculateVal() {
var res = 0;
for (var i = 1; i < 3; i++) {
res = res + +document.getElementById('y' + i).value;
}
var items = document.getElementById("items");
var result = document.createElement('div');
result.innerHTML = res;
items.appendChild(result);
}
<div id="items"></div>
A better way is ...
When you create elements, you can assign them a CLASS attribute that is one for all input elements. You can then take the values from all elements with this class.
Example:
calckStart();
function calckStart() {
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type", "text");
inpt.setAttribute("style", "margin:5px;");
// inpt.setAttribute("id", "y" + i);
inpt.setAttribute("value", "");
inpt.setAttribute("class", "numbers"); //<-- Set class
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
var button = document.createElement('button');
button.innerHTML = 'ClickMe'
items.appendChild(button);
button.addEventListener('click', calculateVal);
}
function calculateVal() {
var list = document.getElementsByClassName('numbers'); //<-- Get by class
var res = 0;
for (var i = 0; i < list.length; i++) {
res = res + +list[i].value;
}
var items = document.getElementById("items");
var result = document.createElement('div');
result.innerHTML = res;
items.appendChild(result);
}
<div id="items"></div>
You can use ...args to collect arguments and use .reduce to add the arguments together.
const items = document.getElementById("items");
for (var i = 0; i < 3; i++) {
var inpt = document.createElement("input");
inpt.setAttribute("type","number"); //replaced with number
inpt.setAttribute("style","margin:5px;");
inpt.setAttribute("id","y"+i);
inpt.setAttribute("value","");
var newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline); //added newline appending
}
function sum(...args) {
return args.reduce((a, b) => a+b); //reduce arguments
}
<div id="items"></div><br /><button onclick="document.getElementById('answer').textContent = 'answer: ' + sum(+y0.value, +y1.value, +y2.value)">Add</button><div id="answer"></div>
** I need new logics to store guessed letters in correct place. A game called hangman. As it is now the previous correct letter is overwritten if a new correct guess applys....**
function guessLetter() {
var letter;
var i;
var letterFound;
var correctLettersCount;
correctLettersCount=0;
letterBoxes = "";
letter = this.value;
for (i = 0; i < selectedWord.length; i++) {
if (selectedWord.charAt(i) == letter) { //if
letterBoxes += "<span>" + letter + "</span >";
}
else{
letterBoxes += "<span>*</span>";
}
document.getElementById("letterBoxes").innerHTML = letterBoxes;
}
}
You can use an array that will store the * and letters found
In the following snippet, this array is called display
const wordToFind = "testing";
const wordDisplay = document.getElementById("word");
let display = Array.from('*'.repeat(wordToFind.length));
wordDisplay.innerHTML = display.join("");
function checkLetter(el){
const letter = el.value.toLowerCase();
for(let i=0,l=wordToFind.length;i<l;i++){
if(wordToFind[i]===letter)
display[i] = letter;
}
el.value = "";
wordDisplay.innerHTML = display.join("");
}
<input oninput="checkLetter(this)" />
<p id="word"></p>
how i get information from array and send it to input?
i have a filter, after filtering information i have 2 value (v1,v2) and 2 button - for v1 and v2. I need to do- by pressing the button v1 information from mynewvarv1 go to input whith id='one' - can you help me to write this function?
sorry for my english
var myvar = [ // filter start
{name:'v1',val1:'31',val2:'',val3:true,val4:false,val5:false,val6:false,},
{name:"Срочный на 91 день",val1:'91',val2:'',val3:true,val4:false,val5:false,val6:false,},
{name:"v2",val1:'181',val2:'',val3:true,val4:false,val5:false,val6:false,},
];
document.getElementById('filterButton').onclick = function(){
var filter = [];
filter.push(document.getElementById('val1').options[document.getElementById('val1').selectedIndex].value);
filter.push(document.getElementById('val2').value);
filter.push(rbvalue('val3')=='1');
filter.push(rbvalue('val4')=='1');
filter.push(rbvalue('val5')=='1');
var filtered_data = [];
var data_accepted = true;
for(i=0;i<myvar.length;i++){
data_accepted = true;
for(j=0;j<filter.length;j++){
if(filter[j]!=='' && filter[j]!=myvar[i][('val'+(j+1))]){
data_accepted = false;
}
}
if(data_accepted){
filtered_data.push(myvar[i]);
}
}
function getmesseg (){
container.innerHTML = ' v1 <button onclick="myFunction()">Try it</button>'
container.innerHTML = ' v2<button onclick="myFunction()">Try it</button>'
var mynewvarv1 = [ {vaal1:value="12",vaal2:'10.2',vaal3:'9',} ];
var mynewvarv2 = [ {vaal1:value="12",vaal2:'10.2',vaal3:'9',} ];
//what the function this needs???
};
function ab(){ if(filtered_data[i].name == "v1","v2") {getmesseg(); }};
var container = document.getElementById('container');
container.innerHTML = '';
for(i=0;i<filtered_data.length;i++){
container.innerHTML+=filtered_data[i].name+'<br />';
ab();
}
};
function rbvalue(html_name){
var undefined,default_value,i,rb_collection = document.getElementsByName(html_name);
if(rb_collection!==undefined){
default_value = rb_collection[0].value;
}
for(i=0;i<rb_collection.length;i++){
if(rb_collection[i].checked){
return rb_collection[i].value;
}
}
return default_value;
}// filter end
You should be able to use:
var input1 = document.getElementById("one");
input1.value = mynewvarv1[0].vaal1;
I need to create 2 arrays in JS from an input value. The first should contain all my inputs values and the second one should contain all my inputs values but for the last one.
I tried this but it doesn't work.
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
var comp = [];
function clickHandler()
{
n = input.value;
for (var i =0; i < 10; i++)
{
valori.push(parseInt(n));
comp = valori.pop();
console.log(valori);
console.log(comp);
break;
}
}
</script>
</body>
The ideea is that I want to check if an input value has been entered before. I thought of doing that by creating 2 arrays like I mentioned before and then compare "n" to the "comp" array
if you are just to check element exist or not.. why dont u why indexOf(n)??
no need to create two array and for loop etc etc.. just indexOf will work for you..
check the below code..
<html>
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
function clickHandler()
{
if(isNaN(input.value))
{
alert('value is not a Number');
}
else
{
var nbr = parseInt(input.value);
if(valori.indexOf(nbr) < 0)
{
valori.push(nbr);
input.value="";
}
else
{
alert('element already exists.');
}
}
}
</script>
</body>
</html>
U are setting value on comp which is array u need to set value at index .
function clickHandler()
{
var is = true;
var n = parseInt(document.getElementById("inp").value);
if(!isNaN(n))
{
for (var i =0; i < valori.length; i++)
{
if(n === valori[i])
{
console.log("duplicate");
is = false;
break;
}
}
if(is)
valori.push(n);
}
console.log(valori);
}
DEMO
I am trying to find the sum of checkbox values (23.75 and 142.75)
Poaten
Checkbox1: 2012-01-17, Porti, 1.760, 23.75
Checkbox2: 2012-01-17, Kopien, 10.560, 142.55
Checkbox3: 2012-01-17, Honorar, 33.600, 453.60
Checkbox4: 2012-01-17, Telefon, 0.640, 8.65
The output is in "Restbetrag". I used the following function but I receive the sum of primary key's value of selected checkbox items in "Posten".
In posten I see four values for each checkbox which are separated by comma. Where should I start to have the 4th value of each clicked checkbox (23.75, 142.55...)? Could you please advice where to find a similar solutions?
Thanks
mpol
function showTotal() {
document.frechnungenadd.x_Restbetrag.value = '';
//document.write("test");
var sum = 0;
var elements = document.getElementsByName("x_Posten[]");
for (i=0;i < elements.length;i++) {
if (elements[i].checked) {
sum = sum + +elements[i].value;
}
}
document.frechnungenadd.x_Restbetrag.value = sum;
}
Not sure if this is what you are looking for...
if (elements[i].checked) {
var myarr = elements[i].value.split(",");
sum += parseFloat(myarr[3]);
}
I solved my problem. Thanks for your support. Here your the code for solution.
Regards
mpol_ch
function showTotal() {
document.frechnungenadd.x_Summe.value = '';
document.frechnungenadd.x_MwSt.value = '';
//document.write("test");
var Summe = 0;
var MwSt = 0
var splitted
var elements = document.getElementsByName("x_Posten[]");
for (i=0;i < elements.length;i++) {
if (elements[i].checked) {
splitted = elements[i].nextSibling.nodeValue.split(",");
MwSt = MwSt+ + parseFloat(splitted[2]);
Summe = Summe+ + parseFloat(splitted[3]);
}
}
document.frechnungenadd.x_MwSt.value = MwSt.toFixed(2);
document.frechnungenadd.x_Summe.value = Summe.toFixed(2);
}
setInterval('showTotal()',1000);