Check sum of inputs before submit - javascript

I need some help: I have the following form:
<form id="myForm" method="post" action="?action=agc">
<input type="hidden" name="start_date" value="<?= $_POST['start_date'] ?>" />
<input type="hidden" name="end_date" value="<?= $_POST['end_date'] ?>" />
<input type="hidden" name="c_name" value="<?= $_POST['c_name'] ?>" />
<input type="hidden" name="cluster" value='<?= $abn_cluster[0] ?>' />
<input type="hidden" name="abn" value="abn" />
Add percent <br /><br />
ABN percent<br />
<input type="text" name="poll[option][0][percent]" class="toAdd"> <input type="text" name="poll[option][0][name]" value="<?= $_POST['c_name'] ?>_0_"> <input type="checkbox" class="optionBox" value="True" name="poll[option][0][control_sample]" /><br />
<script>
var optionNumber = 1;
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
var newOption2 = document.createElement("input");
var newOption3 = document.createElement("input");
var newLabel = document.createElement("label");
var newContent = document.createTextNode(" ");
var newContent2 = document.createTextNode(" ");
newOption.name = "poll[option]["+optionNumber+"][percent]";
newOption.type = "text";
theForm.appendChild(newOption);
theForm.appendChild(newContent);
newOption2.name = "poll[option]["+optionNumber+"][name]";
newOption2.type = "text";
newOption2.value = "<?= $_POST['c_name'] ?>_"+optionNumber+"_"
theForm.appendChild(newOption2);
theForm.appendChild(newContent2);
newOption3.name = "poll[option]["+optionNumber+"][control_sample]";
newOption3.type = "checkbox";
newOption3.className = "optionBox";
newOption3.value = "True"
theForm.appendChild(newOption3);
theForm.appendChild(document.createElement("br"));
optionNumber++;
}
</script>
</p>
</div>
<div class="modal-footer" id="appendform">
<button type="submit" class="btn btn-primary">Continue</button>
</form>
Now because some of the inputs are generated on request, I have no idea how to check the sum of the(.toAdd). And I basically need to make sure that it's equal to 100 before submitting. What would be a solution to my problem? Thanks.

Try
<form id="myForm" method="post" action="iap_crm_campaign.php?action=abngamecampaign" onsubmit="return validate()">
Then
function validate(){
var sum = 0;
for(var i = 0; i < optionNumber; i++){
sum += parseFloat(document.getElementsByName('poll[option][' + i + '][percent]')[0].value);
}
if( sum == NaN || sum != 100){
alert('Sum of percentage must be 100');
return false;
}
}
Demo: Fiddle

var total = 0;
var toAdds = document.getElementsByClassName("toAdd");
for (var i = 0; i < toAdds.length; i++) {
total += parseInt(toAdds[i].value, 0);
}
if (total == 100) {
// OK
} else {
// not OK
}
Also, your code for adding new options needs to set the class:
newOption.className = "toAdd";

you can use jquery
$(".toAdd").length
or in simple js
var myInputs= document.getElementsByTagName('input');
var noOfInputs =myInputs.length;
well this will give you the count of i/p elements through loop, for summing the values...
var sum;
$(".toAdd").each(function() {
sum=sum+$(this).val();
});

Related

Javascript multidimensional array loop from form inputs

I am having a problem with the array of an array. I need the function clickMe() to allow me to output an array such as [[1,1,1,1,1],[2,2,2,2,2],etc].
My problem is that right now the values come up as [1,1,1,1,1,2,2,2,2,2,etc]. I know a for loop inside a for loop would be the best way for this, but how would I get the inputs in sections of five?
Once I can figure this out, I should be able to pull from those arrays without any issues. I would prefer to keep this completely in Javascript.
var qNumber;
function onEnter() {
var qNumber = document.getElementsByName("numberBox")[0].value;
if(event.keyCode == 13) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem("qNumber", qNumber);
console.log(qNumber + " stored successfully");
} else {
console.log("Sorry, your browser does not support Web Storage...");
}
var qID = document.getElementById("numBox");
var submitBtn = document.getElementById("submitButton");
var a = qNumber - 1;
var b = 0;
while (b < a) {
var formClone = document.getElementsByClassName("formBox")[0];
var listClone = formClone.cloneNode(true);
var text =b+2;
document.getElementById("forms").append(listClone);
b++;
}
return qID.parentNode.removeChild(qID);
}
return qNumber;
}
function clickMe() {
var q = localStorage.getItem("qNumber");
console.log(q);
var inputNow = [];
var allInputs = [];
var eachArray = [];
var inputNow = document.getElementsByTagName("input");
for(x=0; x < inputNow.length; x++) {
allInputs.push(inputNow[x].value);
console.log(allInputs);
}
localStorage.clear();
}
input{
display: block;
}
<div id="forms">
<span id="numBox">
<label for="numberBox">Number of Forms</label>
<input type="number" name="numberBox" onkeydown="onEnter()" />
</span>
<form id="formBox" name="formBox" action="#" onsubmit="return false;">
<label for="info1">Input 1:</label>
<input type="text" name="info1" />
<label for="info2">Input 2:
</label>
<input type="text" name="info2" />
<label for="info3">Input 3:
</label>
<input type="text" name="info3" />
<label for="info4">Input 4:
</label>
<input type="text" name="info4" />
<label for="info5">Input 5:
</label>
<input type="text" name="info5" />
</form>
</div>
<input type="submit" value="Submit" id="submitButton" onclick="clickMe()" />
<div id="content">
<span id="info1">input1</span>
<br/>
<span id="info2">input2</span>
<br/>
<span id="info3">input3</span>
<br/>
<span id="info4">input4</span>
<br/>
<span id="info5">input5</span>
</div>
You can always do something like:
var allInputs = [];
var groupInputs = [];
for (x=0; x < inputNow.length; x++) {
groupInputs.push(inputNow[x].value);
if (groupInputs.length === 5 || x === inputNow.length - 1) {
allInputs.push(groupInputs);
groupInputs = [];
}
}

how to auto sum multiple inputbox inner loop in javascript

I want to calculate my input box inner looping and this bellow is what if done please help me to solve this issue
<?php
$jumlah_form = 3;
for($i=1; $i<=$jumlah_form; $i++){
?>
<input type="text" id="txt1" onkeyup="sum1();" /></br>
<?php
}
?>
<input type="text" id="txt2" value= "0" /></br>
<script>
function sum1() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtFirstNumberValue) ;
if (!isNaN(result)) {
document.getElementById('txt2').value = result;
}
}
</script>
Three input boxes are created by looping, I want to calculate three input box, and parse the result into result box whenever user input number
I think you are asking how to write the JavaScript so that it will add up the total of all the input boxes, no matter how many are created by the PHP?
If so then a good way would be to give all the textboxes the same class. Then, the JavaScript can just select all boxes with that class, loop through them and get the total value.
Here's a worked example using 3 textboxes (as if the PHP had generated them this way):
var textboxes = document.querySelectorAll(".sum");
textboxes.forEach(function(box) {
box.addEventListener("keyup", sumAll);
});
function sumAll() {
var total = 0;
textboxes.forEach(function(box) {
var val;
if (box.value == "") val = 0;
else val = parseInt(box.value);
total += val;
});
document.getElementById("total").innerText = total;
}
<input type="number" id="txt1" class="sum" value="0" /><br/>
<input type="number" id="txt2" class="sum" value="0" /><br/>
<input type="number" id="txt3" class="sum" value="0" /><br/>
<br/><br/> Total: <span id="total"></span>
To generate html with php:
$count = 5;
for($i=1;$i <= $count;$i++) {
echo "<input type='number' id='"."txt".i."' /></br>"
}
To calculate sum from inputs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<form onsubmit="submitForm(this); return false;" >
<input type="number" id='text1'>
<input type="number" id='text2'>
<input type="number" id='text3'>
<input type="number" id='text4'>
<input type="number" id='text5'>
<button type="submit" >Calculate</button>
</form>
<div>
<p>Result:</p>
<p id='result'></p>
</div>
<script>
function submitForm(form) {
let toReturn = 0;
const inputs = form.getElementsByTagName("input");
for(let x = 0; x < inputs.length; x++ ) {
toReturn += parseInt(inputs[x].value ? inputs[x].value : 0);
}
document.getElementById('result').innerHTML = toReturn;
return false;
}
</script>
</body>
</html>

how to add n number of input value with javascript

Friends, I want the sum of the numbers I put in fields and these input value total are equal to my total value. it show a Nan Error When i add these input values please help
This is my body Content
<form action="" method="post">
<input type="text" name="cnum" placeholder="enter no. of input">
<input type="submit" name="submit" >
</form>
<?php
if(isset($_POST['cnum']))
{
$cnum=$_POST['cnum'];
$i=0;
?>
<form action="" method="post">
<input type="hidden" name="total" id="total" value="10">
<input type="hidden" name="cnum" id="cnum" value="<?php echo $cnum ;?>">
<?php
while($i<$cnum)
{
?>
<input type="number" id="aq<?php echo $i; ?>" onKeyup="add()" name="aq<?php echo $i; ?>"><br />
<?php
$i++;
}
?>
<input type="submit" name="aqsub">
</form>
<?php
}
?>
This is my java script function
var val=0;
var total=document.getElementById('total').value;
var cnum=document.getElementById('cnum').value;
var anum;
function add()
{
var n=0;
while(n<cnum)
{
anum = 0;
if(document.getElementById('aq'+n).value != "") {
anum=parseInt(document.getElementById('aq'+n).value);
}
val += anum;
n++;
}
alert(val);
}
Update JS part:
var total=document.getElementById('total').value;
total = parseInt(total);
var cnum=document.getElementById('cnum').value;
cnum= parseInt(cnum);
function add()
{
var anum;
var val=0;
var n=0;
while(n<cnum)
{
anum = 0;
var temp = document.getElementById('aq'+n).value;
if( temp != "") {
anum=parseInt(temp);
}
val = +val + anum;
n++;
}
alert(val);
}
var total=document.getElementById('total').value;
total = parseInt(total);
var cnum=document.getElementById('cnum').value;
cnum= parseInt(cnum);
function add()
{
var anum;
var val=0;
var n=0;
while(n<cnum)
{
anum = 0;
var temp = document.getElementById('aq'+n).value;
if( temp != "") {
anum=parseInt(temp);
}
val = +val + anum;
n++;
}
alert(val);
}
<form action="" method="post">
<input name="total" id="total" value="10" type="hidden">
<input name="cnum" id="cnum" value="10" type="hidden">
<input id="aq0" onkeyup="add();" name="aq0" value="" type="number"><br>
<input id="aq1" onkeyup="add();" name="aq1" value="" type="number"><br>
<input id="aq2" onkeyup="add();" name="aq2" value="" type="number"><br>
<input id="aq3" onkeyup="add();" name="aq3" value="" type="number"><br>
<input id="aq4" onkeyup="add();" name="aq4" value="" type="number"><br>
<input id="aq5" onkeyup="add();" name="aq5" value="" type="number"><br>
<input id="aq6" onkeyup="add();" name="aq6" value="" type="number"><br>
<input id="aq7" onkeyup="add();" name="aq7" value="" type="number"><br>
<input id="aq8" onkeyup="add();" name="aq8" value="" type="number"><br>
<input id="aq9" onkeyup="add();" name="aq9" value="" type="number"><br>
Add Following code in your javascript
cnum = parseInt(cnum);
Update code as:
var total= parseInt(document.getElementById('total').value);
As you are using total to comparing with anum. so must be error Nan for total
Well I don't understand your logic but you get NAN because your value of fields are blank.
try this code
var val=0;
var total=document.getElementById('total').value;
var cnum=document.getElementById('cnum').value;
var anum;
function add()
{
var n=0;
while(n<cnum)
{
anum = 0;
if(document.getElementById('aq'+n).value != "") {
anum=parseInt(document.getElementById('aq'+n).value);
}
val += anum;
n++;
}
if(total==anum)
{
alert('Its Work');
}
else
{
alert('Its not Work');
}
}
why dont you directly include the PHP var into a JS var?
var cnum=<?php echo $cnum ;?>;
Also may check against "", and then use a zero
parseInt(input.value)||0;

Dynamic Javascript Div

Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/

how to disable form submit and check the form

I have the following code. I need to see how many checkboxes have been checked in my form and if there are 4 or less submit the form and if there are more display an error and don't submit.
function SetHiddenFieldValue()
{
var checks = document.getElementById('toppings').getElementsByTagName('input');
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var totalChecked = 0;
var itemPrice = 5.99;
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
}
And my form is:
<form id="pizza" name="pizza" method="post" action="" class="jcart" onsubmit="return SetHiddenFieldValue();">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<input type="submit" name="my-add-button" value=" add " />
</form>
any help would be appreciated.
Your javascript looks correct. I think the only you should need to do is return false; on your if (totalChecked > 4) statement.
Edit: Here's the section of your javascript function to modify:
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
return false;
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
return true;
}
Your function needs to return false to cancel the submission or true to proceed. That's why your onsubmit form attribute is set to "return XXX()" rather than just "XXX()"
As mentioned, you should return false from your check function to cancel the submit, and true if the check is okay.
How about something like this?
<html>
<head>
<title>Pizza Order Form</title>
</head>
<body>
<script>
function SetHiddenFieldValue() {
var totalChecked = 0;
var itemPrice = 5.99;
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var checks = document.getElementsByName('topping');
for (i = 0; i < checks.length; i++) {
if (checks[i].checked) {
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
return false;
}
else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
return true;
}
}
</script>
<form id="pizza" name="pizza" method="post" action="" class="jcart" onsubmit="return SetHiddenFieldValue();">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<div id="toppings">
<input type="checkbox" name="topping" id="pepperoni" />Pepperoni
<input type="checkbox" name="topping" id="tomato" />Tomato
<input type="checkbox" name="topping" id="mushrooms" />Mushrooms
<input type="checkbox" name="topping" id="peppers" />Peppers
<input type="checkbox" name="topping" id="olives" />Olives
</div>
<input type="submit" name="my-add-button" value=" Add " />
</form>
</body>
</html>

Categories

Resources