I'm trying to make a small calculator with input elements. I've built a plus button to insert a new input field after the last one. It's working.
Now I'm trying to sum each input field. But I get undefined in the console. I don't know what's wrong because I'm new to programming. I tried to get the value of the input fields with class .input-time and then making it into an array. And then doing a for loop to sum them.
EDIT:
Thanks at all for the help. I used @Yoiki's code because it's a new and easy way. I edited the code snipped. It's working now.
$(function() {
// ADDING NEW INPUT FIELD
$('.button-plus').on('click', function(event) {
event.preventDefault();
let inPut = $('.input-time');
let inPutArr = jQuery.makeArray( inPut );
// console.log(inPutArr);
let lastInPut = inPutArr[inPutArr.length-1]; // get last elem of array
$(lastInPut).addClass('lastone'); // add class to it
$('.lastone').after('<input type=\"text\" class=\"input-time\">');
$('.lastone').delay(10).removeClass('lastone');
});
/* OLD CODE - NOT WORKING!!!
$('#button-calc').on('click', function(event) {
event.preventDefault();
let inPutV = $('.input-time').val();
let inPutVal = jQuery.makeArray( inPutV );
for (var i = 0; i < inPutVal.length; i++) {
var sum = sum + inPutVal[i];
}
console.log(sum);
});
*/
// NEW CODE - WORKING!!!
$('#button-calc').on('click', function(event) {
event.preventDefault();
let sum = 0;
$('.input-time').each (function () {
sum += +$(this).val();
});
console.log (sum);
});
});
/* IGNORE THE STYLE ;) */
input {
width: 160px;
height: 20px;
padding: 10px 20px 10px 20px;
border: none;
border-radius: 20px;
font-size: 15px;
display: block;
margin-bottom: 10px;
}
.container {
background-color: #dde4fe;
padding: 20px;
width: 200px;
margin-right: 20px;
margin-left: auto;
margin-right: auto;
margin-top: 100px;
}
.button-plus {
width: 40px;
height: 40px;
background-color: #9aadfd;
color: #fff;
cursor: pointer;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
border-radius: 20px;
display: flex;
align-items: center;
justify-content: center;
}
#button-calc {
width: 200px;
height: 40px;
background-color: #5677fc;
color: #fff;
cursor: pointer;
margin-top: 20px;
margin-bottom: 0;
}
.btn-plus {
width: 20px;
margin-left: auto;
margin-right: auto;
height: 5px;
background-color: #5677fc;
border-radius: 5px;
position: absolute;
}
.plus-1 {
transition: 0.5s;
transform: rotate(0deg);
}
.plus-2 {
transition: 0.5s;
transform: rotate(90deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="container">
<div class="container-inner">
<input type="text" class="input-time">
<input type="text" class="input-time">
<div class="button-plus">
<div class="btn-plus plus-1"></div>
<div class="btn-plus plus-2"></div>
</div>
<input type="submit" id="button-calc" value="Calculate">
</div>
</section>