Math through multiple inputs - javascript

getting no errors but trying to loop through all the inputs and add them all to the total (var = paidTotal). The first input works but the rest don't when others are added with an add button. Something wrong with the loop?
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = document.getElementById('check').value;
var personsCheck = document.getElementById('personsCheck').value;
var paidTotal = document.getElementById('paidTotal');
for(var i = 1; i < personsCheck.length; i+=1){
personsCheck[i] += paidTotal;
}
paidTotal.innerHTML = checkTotal - personsCheck;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>

make it as class
<input type="text" class="personsCheck" name="person">
and access it by
var personsCheck = document.getElementsByClassName('personsCheck');

ids have to be unique. You'll only get one element from document.getElementById().
Try using a class instead, something like
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
and use document.getElementsByClassName('persons') to get an array of all of the input fields that have that class.

Your code logic is not something what you want to achieve.
I can not find any logic to use the input element with id=personsCheck.
First of all, you are appending input element with same id again and again which is invalid, because in a document id attribute must be unique. Use class attribute instead.
To get the total you can first get the elements with querySelectorAll(), theb use forEach() to loop through all of them to add one by one.
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = Number(document.getElementById('check').value);
var persons = document.querySelectorAll('.persons');
var personsCheck = Number(document.getElementById('personsCheck').value)
var paidTotal = document.getElementById('paidTotal');
var total = 0;
persons.forEach(function(p){
total += Number(p.value);
});
paidTotal.textContent = checkTotal - total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>

Related

Calculate total sum of all the numbers previously entered in a field

i want to calculate the total of the numbers entered by the user. After a user has added item name and the amount, i want to display the total. How can i do this? i just need to display the total.
For example
item name : 10
item name : 5
total = 15
http://jsfiddle.net/81t6auhd/
<body>
<header>
<h1>Exercise 5-2</h1>
</header>
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
<script>
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
</script>
</body>
you have to stored the previous value somewhere in memory to be able to reuse it at next iteration
one proposal can be to stored it in dataset of the field
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount;
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">

Removing a class and adding another class (Appending the HTML tag onclick)

Would I be able to add a remove button to replace the add button as of the image below and remove the values in that row from the array object that I have declared whenever I remove a certain row?
Image of the html (Partly)
Before Clone
After Clone
Desired Result
Html page
<div id="selections">
<div class="form-group row controls selection">
<label for="selection01" class="col-sm-2 col-form-label">Selection Pair</label>
<div class="col-sm-2">
<select class="form-control selection01" id="selection010" placeholder="Selection 01" onchange="addNewSelection()"></select>
</div>
<div class="col-sm-2">
<select class="form-control selection02" id="selection020" placeholder="Selection 02" onchange="addNewSelection()"></select>
</div>
<div class="col-sm-2">
<input type="number" min="0.00" max="10000.00" step="1.00" class="form-control" id="productQuantity0" placeholder="Quantity">
</div>
<div class="col-sm-2">
<input type="button" class="btn btn-success" id="addSelection" value="Add Selection" onclick="addNewSelectionPair()"></button>
</div>
</div>
</div>
Script
function addNewSelectionPair() {
// Get all selections by class
var selection = document.getElementsByClassName('selection');
// Get the last one
var lastSelection = selection[selection.length - 1];
// Clone it
var newSelection = lastSelection.cloneNode(true);
// Update the id values for the input
newSelection.children[1].children[0].id = 'selection01' + selection.length;
newSelection.children[2].childrne[0].id = 'selection02' + selection.length;
newSelection.children[3].children[0].id = 'productQuantity' + selection.length;
// Add it to selectionss
document.getElementById('selections').appendChild(newSelection)
}
function getValues() {
// Get all selections by class
var selections = document.getElementsByClassName('selection');
var values = [];
for(var i = 0; i < selections.length; i++) {
// Add the values into the array
values.push([
document.getElementById('selection01' + i).value,
document.getElementById('selection02' + i).value
document.getElementById('productQuantity' + i).value
]);
}
return values;
}
This script will duplicate the last row of inputs. It will also collect the inputs and store their values in a 3d array to process.
function addSection() {
//Get all sections by class
var sections = document.getElementsByClassName('section');
//Get the last one
var lastSection = sections[sections.length - 1];
//Clone it
var newSection = lastSection.cloneNode(true);
//Add it do sections
document.getElementById('sections').appendChild(newSection);
//Recalucate the Ids for the removal
//Ids all get shifted after adding or removing a section
calcRemovalIds();
}
function getValues() {
//Get all inputs by class
var sectionsOne = document.getElementsByClassName('section01');
var sectionsTwo = document.getElementsByClassName('section02');
var values = [];
//Loop the inputs
for(var i = 0; i < sectionsOne.length; i++) {
//Add the values to the array
values.push([
sectionsOne[i].value,
sectionsTwo[i].value
]);
}
return values;
}
function removeSection(id = undefined) {
//Get all sections by class
var sections = document.getElementsByClassName('section');
//If there is only one row left, just skip
if (sections.length == 1) return true;
//If not id was given, remove the last row
if (id == undefined) id = sections.length - 1;
//Get the last one
var lastSection = sections[id];
//Remove it
lastSection.parentNode.removeChild(lastSection);
//Recalucate the Ids for the removal
//Ids all get shifted after adding or removing a section
calcRemovalIds();
}
function calcRemovalIds() {
var btns = document.getElementsByClassName('button');
for (var i = 0; i < btns.length; i++) {
//Check if its the last button
if (i + 1 == btns.length) {
//Make it a addSection button
btns[i].innerHTML = '+';
btns[i].setAttribute('onclick', 'addSection()');
} else {
//Make is a removeSection button
btns[i].innerHTML = '-';
btns[i].setAttribute('onclick',
'removeSection(' + i +')'
);
}
}
}
<div>
<div>
<h2>Product</h2>
<input id="product" placeholder="Product" />
</div>
<div id="sections">
<div class="section">
<input class="section01" placeholder="Section One" />
<input class="section02" placeholder="Section Two" />
<button class="button" onclick="addSection()">+</button>
</div>
</div>
</div>
<button onclick="
document.getElementById('values').innerHTML = JSON.stringify(getValues());
">Get Values</button>
<div id="values"></div>

Dynamiclly append different class with increment numereic value by click event

I have a span tag and a button tag
<span class="myspan">1</span>
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}
I want to append more span tag with new class from this array with increment value by clicking button.
Like this output:
<span class="myspan1">1</span>
<span class="myspan2">2</span>
<span class="myspan3">3</span>
<span class="myspan4">4</span>
i try `
this JsFiddle
But i can not add class name to new append tag from array.
Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here
value increaseesenter code here this snippet
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
another attempt...anyone can help.. to get desire output
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;
$("#add").click( function() {
(i < elements.length){
$(".new-field").append('<span class="myspan">1</span><script');
var value = parseInt($(".myspan").text(), 10) + 1;
elements[i].className += ' ' + backgrounds[i%len];
i++;
$(".background").text(i);
}
});
*/
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
Try this check the span length via parseInt($(".myspan").length) .And use with Array#forEach for iterate the array instead of increment i.parseInt used convert ths string to number
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var len = backgrounds.length;
$("#add").click( function() {
var len = parseInt($(".myspan").length)
backgrounds.forEach(function(a){
$(".new-field").append('<span class="'+a+'">'+(len++)+'</span>');
})
console.log($(".new-field").html())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
Check the fiddle. Hope this helps!
HTML :
<div id="mainContainer">
<span class="myspan">1</span>
</div>
<button id="add">Add +1</button>
JS :
var arr = ["myspan1", "myspan2", "myspan3", "myspan4"];
$("#add").on("click", function() {
var spans = $("span");
var classList = [];
$.each(spans, function() {
var elemCls = $(this).attr('class').length > 1 ? $(this).attr('class').split(' ') : $(this).attr('class');
if (elemCls) {
$.each(elemCls, function() {
classList.push(this.toString());
});
}
});
$.each(arr, function(i, e) {
if ($.inArray(e, classList) == -1) {
$("#mainContainer").append("<span class='" + e + "'>" + parseInt(spans.length + 1) + "</span>");
return false;
}
});
});

JQuery - Use the value from a function

How can I use the value from a function in an if statement. I have a form where I was using return false in my script but I need changed it to preventDefault.
<form id="percentageBiz" method="post">
<input type="text" id="sum1">
<input type="text" id="sum2">
<input type="submit" onclick="return" value="Get Total">
</form>
<div id="display"></div>​
<script>
$('#percentageBiz').submit(function(e) {
var a = document.forms["percentageBiz"]["sum1"].value;
var b = document.forms["percentageBiz"]["sum2"].value;
var display=document.getElementById("display")
display.innerHTML=parseInt(a,10)+parseInt(b,10);
e.preventDefault();
});
if (display < 100) {
$("#display").addClass("notequal");
}
</script>
$('#percentageBiz').submit(function(e) {
e.preventDefault();
var $display = $("#display", this);
var a = $("#sum1", this).val();
var b = $("#sum2", this).val();
var sum = +a + +b;
$display.text( sum );
if ( sum < 100 ) {
$display.addClass("notequal");
}
});

Changing the name of filedset elements while cloning with javascript

I have a requirement in which I had to add a duplicate of the existing fieldset in a form. I'm able to achieve the cloning process successfully. But I'm not able to change the name and id of the filedset elements. It is the same as the first fieldset but I want it to be with a different name and id to differentiate it(even adding a number at the end would be fine). Below are my js and fieldset.
<div id="placeholder">
<div id="template">
<fieldset id="fieldset">
<legend id="legend">Professional development</legend>
<p>Item <input type ="text" size="25" name="prof_itemDYNID" id ="prof_item_id"/><br /></p>
<p>Duration <input type ="text" size="25" name="prof_durationDYNID" id="prof_duration_id" /><br /></p>
<p>Enlargement <label for="enlargement"></label><p></p>
<textarea name="textareaDYNID" cols="71" rows="5" id="prof_enlargement">
</textarea></p>
<p><input type="button" value="Add new item" id="add_prof" onclick="Add();" /></p>
</fieldset>
</div>
</div>
function Add() {
var oClone = document.getElementById("template").cloneNode(true);
document.getElementById("placeholder").appendChild(oClone);
}
Also, this is just a sample fieldset and it will be different as well. I heard that this can be done using regex but not sure how to do it. Please help.
Not sure this could be achieve using regex, but somewhat following code should work...
var copyNode = original.cloneNode(true);
copyNode.setAttribute("id", modify(original.getAttribute("id")));
document.body.appendChild(el);
Here comes the best(as per my assumption) answer to the above problem..
function addMe(a){
var original = a.parentNode;
while (original.nodeName.toLowerCase() != 'fieldset')
{
original = original.parentNode;
}
var duplicate = original.cloneNode(true);
var changeID= duplicate.id;
var counter = parseInt(changeID.charAt(changeID.length-1));
++counter;
var afterchangeID = changeID.substring(0,changeID.length-1);
var newID=afterchangeID + counter;
duplicate.id = newID;
var tagNames = ['label', 'input', 'select', 'textarea'];
for (var i in tagNames)
{
var nameChange = duplicate.getElementsByTagName(tagNames[i]);
for (var j = 0; j < nameChange.length; j++)
{if (nameChange[j].type != 'hidden'){
var elementName = nameChange[j].name;
var afterSplitName = elementName.substring(0,elementName.length-1);
nameChange[j].name = afterSplitName + counter;
var elementId = nameChange[j].id;
var afterSplitId = elementId.substring(0,elementId.length-1);
nameChange[j].id = afterSplitId + counter;
}
}
}
insertAfter(duplicate, original);
}
function insertAfter(newElement, targetElement)
{
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
{
parent.appendChild(newElement);
}
else
{
parent.insertBefore(newElement, targetElement.nextSibling);
}
}

Categories