jQuery(document).ready(function() {
jQuery().invoice({
addRow: "#addRow",
delete: ".delete",
parentClass: ".item-row",
no: ".no",
price: ".price",
qty: ".qty",
total: ".total",
totalQty: "#totalQty",
subtotal: "#subtotal",
discount: "#discount",
shipping: "#shipping",
grandTotal: "#grandTotal"
});
});
(function(jQuery) {
$.opt = {}; // jQuery Object
jQuery.fn.invoice = function(options) {
var ops = jQuery.extend({}, jQuery.fn.invoice.defaults, options);
$.opt = ops;
var inv = new Invoice();
inv.init();
jQuery('body').on('click', function(e) {
var cur = e.target.id || e.target.className;
if (cur == $.opt.addRow.substring(1))
inv.newRow();
if (cur == $.opt.delete.substring(1))
inv.deleteRow(e.target);
inv.init();
});
jQuery('body').on('keyup', function(e) {
inv.init();
});
return this;
};
}(jQuery));
function Invoice() {
self = this;
}
Invoice.prototype = {
constructor: Invoice,
init: function() {
this.calcTotal();
this.calcTotalQty();
this.calcSubtotal();
this.calcGrandTotal();
},
/**
* Calculate total price of an item.
*
* #returns {number}
*/
calcTotal: function() {
jQuery($.opt.parentClass).each(function(i) {
var row = jQuery(this);
var total = row.find($.opt.price).val() * row.find($.opt.qty).val();
total = self.roundNumber(total, 2);
row.find($.opt.total).val(total);
});
return 1;
},
/***
* Calculate total quantity of an order.
*
* #returns {number}
*/
calcTotalQty: function() {
var totalQty = 0;
jQuery($.opt.qty).each(function(i) {
var qty = jQuery(this).val();
if (!isNaN(qty)) totalQty += Number(qty);
});
totalQty = self.roundNumber(totalQty, 2);
jQuery($.opt.totalQty).val(totalQty);
return 1;
},
/***
* Calculate subtotal of an order.
*
* #returns {number}
*/
calcSubtotal: function() {
var subtotal = 0;
jQuery($.opt.total).each(function(i) {
var total = jQuery(this).val();
if (!isNaN(total)) subtotal += Number(total);
});
subtotal = self.roundNumber(subtotal, 2);
jQuery($.opt.subtotal).val(subtotal);
return 1;
},
/**
* Calculate grand total of an order.
*
* #returns {number}
*/
calcGrandTotal: function() {
var grandTotal = Number(jQuery($.opt.subtotal).val()) +
Number(jQuery($.opt.shipping).val()) -
Number(jQuery($.opt.discount).val());
grandTotal = self.roundNumber(grandTotal, 2);
jQuery($.opt.grandTotal).val(grandTotal);
return 1;
},
/**
* Add a row.
*
* #returns {number}
*/
newRow: function() {
jQuery(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-btn"><a class=' + $.opt.delete.substring(1) + ' href="javascript:;" title="Remove row">X</a><input type="text" class="form-control no p-0 text-center" placeholder="No" type="text"></div></td><td class="item-name"><input type="text" class="form-control item p-0" placeholder="Item" type="text"></td><td><input class="form-control qty p-0 text-center" placeholder="Qty" type="text"></td><td><input class="form-control price p-0 text-center" placeholder="Price" type="text"></td><td><input class="form-control total" type="text" readonly></td></tr>');
if (jQuery($.opt.delete).length > 0) {
jQuery($.opt.delete).show();
}
return 1;
},
/**
* Delete a row.
*
* #param elem current element
* #returns {number}
*/
deleteRow: function(elem) {
jQuery(elem).parents($.opt.parentClass).remove();
if (jQuery($.opt.delete).length < 2) {
jQuery($.opt.delete).hide();
}
return 1;
},
/**
* Round a number.
* Using: http://www.mediacollege.com/internet/javascript/number/round.html
*
* #param number
* #param decimals
* #returns {*}
*/
roundNumber: function(number, decimals) {
var newString; // The new rounded number
decimals = Number(decimals);
if (decimals < 1) {
newString = (Math.round(number)).toString();
} else {
var numString = number.toString();
if (numString.lastIndexOf(".") == -1) { // If there is no decimal point
numString += "."; // give it one at the end
}
var cutoff = numString.lastIndexOf(".") + decimals; // The point at which to truncate the number
var d1 = Number(numString.substring(cutoff, cutoff + 1)); // The value of the last decimal place that we'll end up with
var d2 = Number(numString.substring(cutoff + 1, cutoff + 2)); // The next decimal, after the last one we want
if (d2 >= 5) { // Do we need to round up at all? If not, the string will just be truncated
if (d1 == 9 && cutoff > 0) { // If the last digit is 9, find a new cutoff point
while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
if (d1 != ".") {
cutoff -= 1;
d1 = Number(numString.substring(cutoff, cutoff + 1));
} else {
cutoff -= 1;
}
}
}
d1 += 1;
}
if (d1 == 10) {
numString = numString.substring(0, numString.lastIndexOf("."));
var roundedNum = Number(numString) + 1;
newString = roundedNum.toString() + '.';
} else {
newString = numString.substring(0, cutoff) + d1.toString();
}
}
if (newString.lastIndexOf(".") == -1) { // Do this again, to the new string
newString += ".";
}
var decs = (newString.substring(newString.lastIndexOf(".") + 1)).length;
for (var i = 0; i < decimals - decs; i++)
newString += "0";
//var newNumber = Number(newString);// make it a number if you like
return newString; // Output the result to the form field (change for your purposes)
}
};
.delete-btn {
position: relative;
}
.delete {
display: block;
color: #000;
text-decoration: none;
position: absolute;
background: #EEEEEE;
font-weight: bold;
padding: 2px 8px;
border: none;
border-radius: 5px;
top: -1px;
left: -16px;
font-family: Verdana;
font-size: 15px;
}
<script src="https://code.jquery.com/jquery-3.6.0.slim.js"></script>
<script src="https://cdn.metroui.org.ua/v4/js/metro.min.js"></script>
<link href="https://cdn.metroui.org.ua/v4/css/metro-all.min.css" rel="stylesheet" />
<table class="table compact table-border cell-border">
<tr class="item-row">
<th class="headNo">No</th>
<th class="headItem">Item</th>
<th class="headQty">Qty</th>
<th class="headPrice">Price</th>
<th class="headTotal">Amount</th>
</tr>
<tbody id="row">
<tr id="hiderow">
<td colspan="5">
<a id="addRow" href="javascript:;" title="Add a row" class="button">+</a>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td class="text-right"><strong>Sub Total</strong></td>
<td><input id="subtotal"></td>
</tr>
<tr>
<td><strong>Total Quantity: </strong><span id="totalQty">0</span> Units</td>
<td></td>
<td></td>
<td class="text-right"><strong>Discount</strong></td>
<td><input class="form-control" id="discount" value="0" type="text"></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td class="text-right"><strong>Shipping</strong></td>
<td><input class="form-control" id="shipping" value="0" type="text"></td>
</tr>
<tr>
<td colspan="3"></td>
<td class="text-center"><strong>Total</strong></td>
<td><input id="grandTotal" class="form-control text-right" type="text" readonly></td>
</tr>
</tbody>
</table>
<button id="btn">Submin</button>
code of invoice in snippet
"No,Item,qty,Price,Amount" works prefect in client side and value of "No,Item,qty,Price,Amount" shown in console but i want to transfer "No,Item,qty,Price,Amount" values in google sheet. I tried using jquery but it only transfer one row data and repeat first row data in second row.How can i do that?
Related
Because I'm too lazy to calculate every time I decided to make a calculator with jquery.
For some reason it's not working and I don't know why so I'm here to ask you guys for help.
Here's a jsfiddle link
Damage Formula:
AbaseEq: Damage Range of weapon (e.g: 800~1000)
up difference: weapon up- armor up (e.g: 5-3:2 -> up difference:2 -> 15% if difference was 1 it would be 10%)
Aeq: AbaseEq(1+up difference in %)
Codes:
<table>
<tr>
<td>
<label>Base Attack (Without any equipment equipped): </label>
</td>
<td>
<input placeholder="e.g: 290" id="abase">
</td>
</tr>
<tr>
<td>
<label>Weapon Attack Range: </label>
</td>
<td>
<input placeholder="e.g: 800-1000" id="abaseeq">
</td>
</tr>
<tr>
<td>
<label>Weapon + ?</label>
</td>
<td>
<input placeholder="e.g: 9" id="weapon+">
</td>
</tr>
<tr>
<td>
<label>Enemy Defence + ? </label>
</td>
<td>
<input placeholder="e.g: 6" id="enemydef+">
</td>
</tr>
<tr>
<td>
<button id="calculate">
Calculate
</button>
</td>
<td>
<div id="result"></div>
</td>
</tr>
</table>
$(document).ready(function() {
$('#calculate').on('click', function() {
var abase = $('#abase').val();
var abaseEq = $('#abaseeq').val();
var abaseEqLength = abaseEq.length;
abaseEqLength -= 1;
var weaponlvl = $('#weaponup').val();
var enemydeflvl = $('#enemydefup').val();
var weaponup=parseInt(weaponlvl);
var enemydefup=parseInt(enemydeflvl);
var updifference = weaponup - enemydefup;
var plusdifference = [0, '10%', '15%', '22%', '32%', '43%', '54%', '65%', '90%', '120%', '200%'];
var negdifference = {};
var result;
var aeqmin=0;
var aeqmax=0;
var lowestdamage="";
var maxdamage="";
var negindex;
var negindexplus = 0;
for (var i = 0; i <= abaseEqLength; i++) {
if (abaseEq[i] == '-') {
negindex = i;
negindexplus += (negindex + 1);
}
}
for (var x = 0; x < negindex; x++) {
lowestdamage = lowestdamage + abaseEq[x];
console.log("Lowest Damage: " + lowestdamage);
}
for (var y = negindexplus; y <= abaseEqLength; y++) {
maxdamage = maxdamage + abaseEq[y];
console.log("Max Damage: " + maxdamage);
}
if (updifference => 0 && updifference <= 10) {
updifference = plusdifference[updifference];
console.log("updifference: "+updifference);
result = "pos";
}
if (updifference < 0 && updifference >= -10) {
var negarray = negdifference * -1;
negdifference[updifference] = plusdifference[negarray];
}
var mindamage = parseInt(lowestdamage);
var maxidamage = parseInt(maxdamage);
if (result == "pos") {
aeqmin = mindamage * (1 + plusdifference[updifference]);
aeqmax = maxidamage * (1 + plusdifference[updifference]);
}
if (aeqmax > 0) {
$('#result').html = aeqmin + "~" + aeqmax;
}
}); // calculate on click function
}); // document ready
I would like to calculate the class average and wanted to store the inputs in different variables. However, the scores are calculating together at once and I have trouble fixing it. Do I use a for loop to repeat the equation? Please help me ! Thanks
Here is my codepen to the code:
https://codepen.io/ivy-chung/pen/GBzmwb?editors=1010
$(document).ready(function() {
//iterate through each textboxes
$('.txtMarks').each(function() {
// call 'calcSumAndAverage' method on keyup handler.
$(this).keyup(function() {
// check value is within range and is a number
if (!isNaN(this.value) && this.value.length != 0 && this.value >= 0 && this.value <= 30) {
calcGradeScore();
} else {
alert("Wrong number, number must be 0-30");
}
});
});
});
function calcGradeScore() {
var total = 0;
var average = 0;
var avgGrade;
var img = document.createElement("img");
//iterate through each textboxes with class name '.txtMarks'and add the values.
$('.txtMarks').each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
total += parseFloat(this.value);
}
});
//Calculate the Average
if (!isNaN(total) && total != 0) {
//Get count of textboxes with class '.txtMarks'
var txtboxes = $('.txtMarks').length;
average = parseFloat(total) / (txtboxes * 0.3);
}
if (average >= 80 && average < 100) {
avgGrade = 'HD-High Distiction';
img.src = "https://memegenerator.net/img/instances/19226146/first-assestment-of-the-year-gets-high-distinction.jpg";
} else if (average >= 70 && average < 79) {
avgGrade = 'D-Distiction';
img.src = "https://memegenerator.net/img/instances/53639165/distinction-why-not-high-distinction.jpg";
} else if (average >= 60 && average < 69) {
avgGrade = 'C-Credit';
img.src = "https://pics.me.me/the-face-you-make-cjthecreditfixer-when-you-check-your-credit-27495760.png";
} else if (average >= 50 && average < 59) {
avgGrade = 'P-Pass';
img.src = "http://images.memes.com/meme/535301";
} else if (average >= 0 && average < 49) {
avgGrade = 'F-Failed';
img.src = "https://www.36ng.ng/wp-content/uploads/2015/09/Exam-fail-3.jpg";
}
//Show Total Marks.
$('#totalMarks').html(total);
// Show Average upto 2 decimal places using .toFixed() method.
$('#average').html(average.toFixed(1) + "%");
// S
$('#grade').html(avgGrade);
//
$('#image').html(img);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Grade Calculator</h1>
<table class="grade-table">
<tr class="label">
<td colspan="2">Please enter student's classwork score out of 30:</td>
</tr>
<tr>
<td>Subject 1:</td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr>
<td>Subject 2: </td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr>
<td>Subject 3:</td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr class="label">
<td class="right">Total Marks :</td>
<td class="center"><span id="totalMarks">0</span></td>
</tr>
<tr class="label">
<td class="right">Average Percentage :</td>
<td class="center"><span id="average">0</span></td>
</tr>
<tr class="label">
<td class="right">Grade:</td>
<td class="center"><span id="grade">0</span></td>
</tr>
<tr class="label">
<td class="right"></td>
<td class="center"><span id="image"></span></td>
</tr>
</table>
<table class="grade-table">
<tr class="label">
<td colspan="2">Please enter student's classwork score out of 30:</td>
</tr>
<tr>
<td>Subject 1:</td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr>
<td>Subject 2: </td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr>
<td>Subject 3:</td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr class="label">
<td class="right">Total Marks :</td>
<td class="center"><span id="totalMarks">0</span></td>
</tr>
<tr class="label">
<td class="right">Average Percentage :</td>
<td class="center"><span id="average">0</span></td>
</tr>
<tr class="label">
<td class="right">Grade:</td>
<td class="center"><span id="grade">0</span></td>
</tr>
<tr class="label">
<td class="right"></td>
<td class="center"><span id="image"></span></td>
</tr>
</table>
As your are using duplicate id for Total Marks, Average Percentage, Grade and image, so instead of using duplicate id use class name and access by
$(this).closest('table').find('.classname')
So will provide you current table element and calculation will be reflect for that particular table.
Working codepen
CODE SNIPPET
$(document).ready(function() {
//iterate through each textboxes
$('.txtMarks').each(function() {
// call 'calcSumAndAverage' method on keyup handler.
$(this).keyup(function() {
// check value is within range and is a number
if (!isNaN(this.value) && this.value.length != 0 && this.value >= 0 && this.value <= 30) {
calcGradeScore($(this).closest('table'));
} else {
alert("Wrong number, number must be 0-30");
}
});
});
});
function calcGradeScore(el) {
var total = 0,
average = 0,
avgGrade,
img = document.createElement("img"),
txtMarks = el.find('.txtMarks');
//iterate through each textboxes with class name '.txtMarks'and add the values.
txtMarks.each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
total += parseFloat(this.value);
}
});
//Calculate the Average
if (!isNaN(total) && total != 0) {
//Get count of textboxes with class '.txtMarks'
var txtboxes = txtMarks.length;
average = parseFloat(total) / (txtboxes * 0.3);
}
if (average >= 80 && average < 100) {
avgGrade = 'HD-High Distiction';
img.src = "https://memegenerator.net/img/instances/19226146/first-assestment-of-the-year-gets-high-distinction.jpg";
} else if (average >= 70 && average < 79) {
avgGrade = 'D-Distiction';
img.src = "https://memegenerator.net/img/instances/53639165/distinction-why-not-high-distinction.jpg";
} else if (average >= 60 && average < 69) {
avgGrade = 'C-Credit';
img.src = "https://pics.me.me/the-face-you-make-cjthecreditfixer-when-you-check-your-credit-27495760.png";
} else if (average >= 50 && average < 59) {
avgGrade = 'P-Pass';
img.src = "http://images.memes.com/meme/535301";
} else if (average >= 0 && average < 49) {
avgGrade = 'F-Failed';
img.src = "https://www.36ng.ng/wp-content/uploads/2015/09/Exam-fail-3.jpg";
}
//Show Total Marks.
el.find('.totalMarks').html(total);
// Show Average upto 2 decimal places using .toFixed() method.
el.find('.average').html(average.toFixed(1) + "%");
// S
el.find('.grade').html(avgGrade);
//
el.find('.image').html(img);
}
you can add the parent selector to calculate the average for each table
<table class="grade-table" id="table1">....</div>
<table class="grade-table" id="table2">....</div>
$(document).ready(function () {
//iterate through each textboxes
$('.txtMarks').each(function(){
// call 'calcSumAndAverage' method on keyup handler.
$(this).keyup(function () {
// check value is within range and is a number
if (!isNaN(this.value) && this.value.length != 0 && this.value >= 0 && this.value<=30) {
calcGradeScore('#'+this.parentElement.parentElement.parentElement.parentElement.id); // td > tr > tbody > table
}else{
alert("Wrong number, number must be 0-30");
}
});
});
});
function calcGradeScore($parentSelector) {
var total = 0;
var average = 0;
var avgGrade;
var img = document.createElement("img");
//iterate through each textboxes with class name '.txtMarks'and add the values.
$($parentSelector +' .txtMarks').each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0 ) {
total += parseFloat(this.value);
}
console.log(total);
});
//Calculate the Average
if (!isNaN(total) && total != 0) {
//Get count of textboxes with class '.txtMarks'
var txtboxes = $($parentSelector +' .txtMarks').length;
average = parseFloat(total) / (txtboxes*0.3);
}
if(average >= 80 && average < 100){
avgGrade = 'HD-High Distiction';
img.src = "https://memegenerator.net/img/instances/19226146/first-assestment-of-the-year-gets-high-distinction.jpg";
}
else if(average >= 70 && average < 79){
avgGrade = 'D-Distiction';
img.src = "https://memegenerator.net/img/instances/53639165/distinction-why-not-high-distinction.jpg";
}
else if(average >= 60 && average < 69){
avgGrade = 'C-Credit';
img.src = "https://pics.me.me/the-face-you-make-cjthecreditfixer-when-you-check-your-credit-27495760.png";
}
else if(average >= 50 && average < 59){
avgGrade = 'P-Pass';
img.src = "http://images.memes.com/meme/535301";
}
else if(average>= 0 && average < 49){
avgGrade = 'F-Failed';
img.src = "https://www.36ng.ng/wp-content/uploads/2015/09/Exam-fail-3.jpg";
}
//Show Total Marks.
$($parentSelector +' #totalMarks').html(total);
// Show Average upto 2 decimal places using .toFixed() method.
$($parentSelector +' #average').html(average.toFixed(1) + "%");
// S
$($parentSelector +' #grade').html(avgGrade);
//
$($parentSelector +' #image').html(img);
}
var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
var set = document.getElementById('winnerCount').value;
if (set.length > sum.length) {
document.getElementById('err_winnerCount').remove();
} else {
document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
document.getElementById("demo").innerHTML = "Rank     Winning%           Winning Amount";
var x = document.getElementById("w_amount").value;
var w = document.getElementById("c_size").value;
var y = document.getElementById("winnerCount").value;
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
for (z = 1; z <= parseInt(y); z++) {
document.getElementById("demo1").innerHTML += +z + " <input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/> <input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert('errr');
$('#err_winnerCount').innerHTML = "Please enter less than contest size";
}
}
var sharePerc = 0;
function getValues(arg) {
var id = arg.getAttribute('id');
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var curPerc = document.getElementById(id).value;
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - curPerc) / (x2.length - 1);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" onblur="validate()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="2"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"></input><span class="err" id="err_winnerCount"></span></li>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</div>
// firstly when giving winning amount and contest size we get the entry fee and after check in customize winning it will enable the set number of winners and set button.In set number of winners the input should be less than the contest size but while entering the greater than contest size it will not showing error message and after clicking set button we get a list of winners in this the winning % should be decreasing order while changing the default winning % of first text box but in my code while changing the second text box it changes the first text box also. if possible please know me how to solve this.
var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
$('#err_winnerCount').html("");
var set = document.getElementById('winnerCount').value;
var contestSize = document.getElementById('c_size').value;
if (set > contestSize) {
$('#err_winnerCount').html("");
} else {
//document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
var x = document.getElementById("w_amount").value;
var w = parseInt(document.getElementById("c_size").value);
var y = parseInt(document.getElementById("winnerCount").value);
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
//document.getElementById("demo").innerHTML = "Rank     Winning%           Winning Amount";
var demoTableBody = document.getElementById("demo_table").tBodies[0];
demoTableBody.innerHTML = "";
//console.log(demoTableBody.innerHTML);
for (z = 1; z <= parseInt(y); z++) {
//console.log(demoTableBody.children.length);
var rowIndex = demoTableBody.children.length + 1;
var newRow = "<td>"+rowIndex+"</td>";
newRow += "<td><input type='text' class='tot' id='perc" + rowIndex + "' value='' onkeyup='getValues(this)'/><span class = 'perc_error_spn' id='perc_error" + rowIndex + "'></span></td>";
newRow += "<td><input type='text' class='pop' id='val" + rowIndex + "' value='Rs." + a + "'/></td>";
demoTableBody.innerHTML += newRow;
//document.getElementById("demo1").innerHTML += +z + " <input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/> <input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert("errr");
$('#err_winnerCount').html("Please enter less than contest size");
}
}
var sharePerc = 0;
function getValues(arg) {
// clear all error messages.
var errorSpans = document.getElementsByClassName("perc_error_spn");
for(var i = 0; i < errorSpans.length; i++){
errorSpans[i].innerHTML = "";
}
var id = arg.getAttribute('id');
var row_index = arg.parentNode.parentNode.rowIndex;
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var tmp = 0;
var previousWinnersPercentage = [];
var nextWinnersPercentage = [];
for(var i = 1; i < row_index; i++){
tmp += parseFloat(document.getElementById("perc" + i).value);
previousWinnersPercentage[previousWinnersPercentage.length] = tmp;
}
for(var i = row_index + 1 ; i <= x2.length; i++){
nextWinnersPercentage[nextWinnersPercentage.length] = parseFloat(document.getElementById("perc" + i).value);
}
//winAmt -= tmp;
var curPerc = document.getElementById(id).value;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var isInvalidInput = isBiggerThanPreviousPercentage(previousWinnersPercentage,curPerc);
if(!isInvalidInput){
isInvalidInput = isLesserThanPreviousPercentage(nextWinnersPercentage,curPerc);
}
if((sharePerc <= 0 && x2.length > 1) || isInvalidInput){
var errorSpan = id.replace("perc", "perc_error");
document.getElementById(errorSpan).innerHTML = "Invalid input";
return;
}
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = row_index; i <= x2.length; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
function reorderPercentage(){
var demoTableBody = document.getElementById("demo_table").tBodies[0];
for(var i = 0; i < demoTableBody.children.length; i++){
var percentageInput = demoTableBody.children[i].querySelector(".tot");
//console.log(percentageInput.value);
var row = percentageInput.parentNode.parentNode,
sibling = row.nextElementSibling,
parent = row.parentNode;
var siblingPercentageValue = "";
//console.log(sibling);
if(sibling != null){
siblingPercentageValue = sibling.querySelector(".tot").value;
}
if(percentageInput.value < siblingPercentageValue){
parent.insertBefore(sibling,row);
}
}
}
function isBiggerThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value > e){
return true;
}
});
return result;
}
function isLesserThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value < e){
return true;
}
});
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="3"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"/><span class="err" id="err_winnerCount"></span>
<input type="button" value="Reorder" onclick="reorderPercentage();"/>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<table id="demo_table">
<thead>
<tr>
<th>Rank</th>
<th>Winning %</th>
<th>Winning Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
table, th, td {
border: 1px solid black;
}
</style>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div class="dropdown">
<button class="dropbtn">10 Winners</button>
<div class="dropdown-content">
<table style="width:100%">
<tr>
<th>Rank</th>
<th>Prize</th>
</tr>
<tr>
<td>1</td>
<td>1000</td>
</tr>
<tr>
<td>2-5</td>
<td>500</td>
</tr>
<tr>
<td>6-10</td>
<td>100</td>
</tr>
</table>
</div>
</div>
</body>
If you input number of winners greater than contest size it will prompt an alert box. Check and let me know that is it working or not?
Due to below code both the text boxes are modified simultaneously.
If you can explain the below code, why you are using this
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
So here is what I have so far. I am very new to javascript. How do I make these dice roll sequentially inside of the divs? Such as only displaying the next random number only after the first one is displayed.
<html>
<style>
.numdiv{
height: 400px;
width: 200px;
border:solid 1px green;
float: left
}
</style>
<head>
<script>
function rollDice(){
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
var number3 = document.getElementById("number3");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var d3 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2 + d3;
number1.innerHTML = d1;
number2.innerHTML = d2;
number3.innerHTML = d3;
status.innerHTML = "You rolled "+diceTotal+".";
if(diceTotal == 15){
status.innerHTML += "You Win!!";
}
}
</script>
</head>
<body>
<table>
<tr>
<td>
<div class="numdiv" id="number1">
0</div>
<div class="numdiv" id="number2">
0</div>
<div class="numdiv" id="number3">
0</div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()"/>Generate Number</button></td></tr>
<tr>
<td><span id="status">0</span></td></tr>
</table>
</body>
</html>
You can use the setTimeout() method to delay execution of a function, so that the dice will be rolled one at a time:
function rollDice(){
var status = document.getElementById("status");
var nums = document.querySelectorAll(".numdiv");
var diceTotal = 0;
var current;
for (current = 0; current < nums.length; current++) {
nums[current].innerHTML = "?";
}
current = 0;
status.innerHTML = "Rolling...";
function rollNext() {
currentRoll = Math.floor(Math.random() * 6) + 1;
nums[current].innerHTML = currentRoll;
diceTotal += currentRoll;
current++;
if (current < nums.length) {
setTimeout(rollNext, 1000);
} else {
status.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 15){
status.innerHTML += "You Win!!";
}
}
}
setTimeout(rollNext, 1000);
}
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px }
<table>
<tr>
<td>
<div class="numdiv" id="number1"></div>
<div class="numdiv" id="number2"></div>
<div class="numdiv" id="number3"></div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()"/>Generate Number</button></td></tr>
<tr>
<td><span id="status">0</span></td>
</tr>
</table>
Notice also that I've removed your separate number1, number2 and number3 variables, instead using a single variable num to refer to the list of all of the .numDiv div elements. That way you can easily change how many dice you want to use without changing the JS at all (you'd just add or remove .numDiv elements).
EDIT: As I was posting the above you clarified that you want the user to press the button for each die, not automatically roll all three with a delay. So I guess, maybe something like the following, keeping a counter and the total in variables declared outside the function:
var statusSpan = document.getElementById("status");
var nums = document.querySelectorAll(".numdiv");
var diceTotal;
var current = 0;
function rollDice(){
if (current === 0) { // reset display
for (var i = 0; i < nums.length; i++)
nums[i].innerHTML = "?";
diceTotal = 0;
}
currentRoll = Math.floor(Math.random() * 6) + 1;
nums[current].innerHTML = currentRoll;
diceTotal += currentRoll;
if (++current < nums.length) {
statusSpan.innerHTML = "Current total: " + diceTotal + ".";
} else {
statusSpan.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 15){
statusSpan.innerHTML += "You Win!!";
}
current = 0;
}
}
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px; text-align: center }
<table>
<tr>
<td>
<div class="numdiv" id="number1"></div>
<div class="numdiv" id="number2"></div>
<div class="numdiv" id="number3"></div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()">Roll next die</button></td></tr>
<tr>
<td><span id="status">Ready to roll?</span></td>
</tr>
</table>
Create a counter variable starting with one outside of your rollDice function and every time that is clicked then increase the counter by one. Then you need to replace all the number variables with just this:
var number = document.getElementById("number" + counter);
I think you know where to go from here. Let me know if you need more guidance!
Building on your existing logic, if you want to display 1 every time user clicks then an alternate approach....
var totalIter = 0;//global var which is set to increments on each click
var diceTotal = 0;
function rollDice() {
totalIter = totalIter + 1; //increment by 1
//Existing logic from your script
var ele = document.getElementById("number" + totalIter);
var d1 = Math.floor(Math.random() * 6) + 1;
var status = document.getElementById("status");
diceTotal = diceTotal + d1;
ele.innerHTML = d1;
status.innerHTML = "You rolled " + diceTotal + ".";
if (diceTotal == 15) {
status.innerHTML += "You Win!!";
}
}
how can I add the inputted data under 'unit cost', 'finance %' and 'freight cost/unit' and output that in 'unit landed cost price'? Here's a screenshot to illustrate http://s18.postimg.org/b1avx0omx/retail_calc.png
Here's the current script supplied.
<script>
var gstPercent = 10.0;
function retailToolkit_UpdateRetailCalculator()
{
var sellPrice = retailToolkit_ValidateFloatInput('txtRetailCalculatorSellPrice');
var costPrice = retailToolkit_ValidateFloatInput('txtRetailCalculatorCostPrice');
var margin = retailToolkit_ValidateFloatInput('txtRetailCalculatorMargin');
var grossMargin = retailToolkit_ValidateFloatInput('txtRetailCalculatorGrossMargin');
var inputCount = 0;
if (!isNaN(sellPrice))
inputCount++;
if (!isNaN(costPrice))
inputCount++;
if (!isNaN(margin))
inputCount++;
if (!isNaN(grossMargin))
inputCount++;
if (inputCount == 2)
{
var sellPriceExGST;
if (isNaN(sellPrice))
{
if (isNaN(costPrice))
{
//we have margin & grossMargin
sellPriceExGST = grossMargin / (margin / 100.0);
costPrice = sellPriceExGST - grossMargin;
sellPrice = sellPriceExGST + (sellPriceExGST * (gstPercent / 100));
}
else if (isNaN(margin))
{
//we have costPrice & grossMargin
sellPriceExGST = costPrice + grossMargin
sellPrice = sellPriceExGST + (sellPriceExGST * (gstPercent / 100));
}
else
{
//we have costPrice & margin
sellPriceExGST = (costPrice / (100 - margin)) * 100;
sellPrice = sellPriceExGST + (sellPriceExGST * (gstPercent / 100));
}
}
else
sellPriceExGST = (sellPrice / (100 + gstPercent)) * 100;
//once we reach here we now definitely have sellPriceExGST & sellPrice
if (isNaN(costPrice))
{
if (!isNaN(grossMargin)) //we have sellPriceExGST & grossMargin
costPrice = sellPriceExGST - grossMargin;
else
{
//we have sellPriceExGST & margin
grossMargin = sellPriceExGST * margin / 100;
costPrice = sellPriceExGST - grossMargin;
}
}
if (isNaN(grossMargin))
grossMargin = sellPriceExGST - costPrice;
if (isNaN(margin))
margin = (grossMargin / sellPriceExGST) * 100;
document.getElementById("spanRetailCalculatorSellPrice").innerHTML = FormatCost(sellPrice, "$", 2);
document.getElementById("spanRetailCalculatorCostPrice").innerHTML = FormatCost(costPrice, "$", 2);
document.getElementById("spanRetailCalculatorMargin").innerHTML = FormatCost(margin, "", 1) + "%";
document.getElementById("spanRetailCalculatorGrossMargin").innerHTML = FormatCost(grossMargin, "$", 2);
}
else
{
document.getElementById("spanRetailCalculatorSellPrice").innerHTML = "";
document.getElementById("spanRetailCalculatorCostPrice").innerHTML = "";
document.getElementById("spanRetailCalculatorMargin").innerHTML = "";
document.getElementById("spanRetailCalculatorGrossMargin").innerHTML = "";
}
}
function retailToolkit_ValidateFloatInput(inputCtrlId)
{
var ctrl = document.getElementById(inputCtrlId);
var flt = parseFloat(ctrl.value);
if (isNaN(flt))
ctrl.value = '';
else
{
var corrected = "";
for (var i = 0; i < ctrl.value.length; i++)
{
if ((ctrl.value[i] >= '0' && ctrl.value[i] <= '9') || ctrl.value[i] == '.')
corrected += ctrl.value[i];
}
ctrl.value = corrected;
}
return flt;
}
</script>`
and the HTML is below.
<tr>
<td>Unit Landed Cost Price (excluding GST), including finance and freight charges</td>
<td>$</td>
<td><span id="spanRetailCalculatorCostPrice"></span><br />
</td>
<td></td>
</tr>
<tr>
<td>
<table>
<tr>
<td>Unit Cost</td>
<td>Finance %</td>
<td>Freight Cost/Unit</td>
</tr>
<tr>
<td><input type="text" onkeyup="return retailToolkit_UpdateRetailCalculator()" id="txtRetailCalculatorCostPrice" /></td>
<td><input type="text" onkeyup="return retailToolkit_UpdateRetailCalculator()" id="txtRetailCalculatorFinancePercentage" /></td>
<td><input type="text" onkeyup="return retailToolkit_UpdateRetailCalculator()" id="txtRetailCalculatorFreightCost" /></td>
</tr>
</table>
</td>
</tr>
<tr>