So I've attempted to create a system for my transactions page so that when a user buys 10 tickets, his total will be 70, however I need it so every ticket after that is sold for normal price. This is where I'm at so far, it works with some examples ( 5 adult 7 student ) for example but not others ( 9 and 2 )
I will be forever grateful if someone can find where I'm going wrong and why some numbers work and others don't. And yes I know my code is a little sloppy I apologize in advance but thank you if you can help!
<form id="newshow" action="required/post/saveTransaction.php" method="post" oninput="
bothTickets.value = Math.round(ticketOne.value) + Math.round(ticketTwo.value);
var basePrice;
var TempAmt;
var newTicketValueOne;
var newTicketValueTwo;
if (bothTickets.value == 10) {
basePrice = 70
ticketOnePrice = 0
ticketTwoPrice = 0
calculation.value = Math.round(ticketOne.value * ticketOnePrice) + Math.round(ticketTwo.value * ticketTwoPrice) + basePrice;
} else if (bothTickets.value >= 10) {
if (ticketOne.value >= 10) {
newTicketValueOne = Math.round(ticketOne.value) - 10;
newTicketValueTwo = Math.round(ticketTwo.value);
} else if (ticketTwo.value >= 10) {
newTicketValueTwo = Math.round(ticketTwo.value) - 10;
newTicketValueOne = Math.round(ticketOne.value);
} else if (ticketOne.value >= 5) {
newTicketValueOne = Math.round(ticketOne.value) - 5;
newTicketValueTwo = Math.round(ticketTwo.value) - 5;
} else if (ticketTwo.value >= 5) {
newTicketValueTwo = Math.round(ticketTwo.value) - 5;
newTicketValueOne = Math.round(ticketOne.value) - 5;
} else {
newTicketValueOne = Math.round(ticketOne.value);
newTicketValueTwo = Math.round(ticketTwo.value);
}
basePrice = 70
ticketOnePrice = 10
ticketTwoPrice = 7
tempAmt = basePrice + Math.round(newTicketValueOne * ticketOnePrice) + Math.round(newTicketValueTwo * ticketTwoPrice);
calculation.value = tempAmt
} else {
basePrice = 0
ticketOnePrice = 10
ticketTwoPrice = 7
calculation.value = Math.round(ticketOne.value * ticketOnePrice) + Math.round(ticketTwo.value * ticketTwoPrice);
}
base.value = basePrice;
//calculation.value = Math.round(ticketOne.value * ticketOnePrice) + Math.round(ticketTwo.value * ticketTwoPrice);
totalAmount.value = Math.round(calculation.value);
changeDue.value = Math.round(moneyGiven.value - totalAmount.value);">
<fieldset>
<input type="hidden" name="teamID" value="<?php echo $_SESSION['teamID']; ?>" />
<h4>Amount of Adults</h4>
<input class="form-control" name="ticketOne" type="number" placeholder="0">
<br />
<h4>Amount of Students</h4>
<input class="form-control" name="ticketTwo" type="number" placeholder="0">
<br />
<h4>Money Owed</h4>
<input class="form-control" name="totalAmount" readonly="1">
<br />
<h4>Money Given</h4>
<input class="form-control" name="moneyGiven" type="number" required>
<h4>Change due</h4>
<input class="form-control" name="changeDue" readonly="1">
<input type="hidden" name="username" value="<?php echo $_SESSION['username']; ?>" />
<input type="hidden" class="form-control" name="bothTickets" readonly="1">
<input type="hidden" class="form-control" name="base" readonly="1">
<input type="hidden" class="form-control" name="calculation" readonly="1">
</fieldset>
<div class="modal-footer">
<button class="btn btn-default" type="button" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Process"/>
</div>
</form>
One advice: don't let the server trust values given from the client, you need to re calculate the amount and change on the server as any user can just post any values to the server.
You can do the following:
var adultTickets = 0,studentTickets=0,monyGiven=0,moneyOwed=0,change=0;
const calculateValues = () => {
if(adultTickets+studentTickets>=10){//discount, more than 10 tickets
const adultLeft = adultTickets-10;//how many of the tickets are adult tickets
if(adultLeft>0){//more than 10 are adult tickets
moneyOwed = 70 + (adultLeft*10) + (studentTickets*7);
}else{//less than 10 are adult tickets
moneyOwed = 70 + ((studentTickets+adultLeft)*7);
}
}else{
moneyOwed = (adultTickets*10) + (studentTickets*7);
}
change = monyGiven-moneyOwed;
}
const setHtml = () => {
document.querySelector(`[name="totalAmount"]`).value=moneyOwed;
if(!(change<0)){
document.querySelector(`[name="changeDue"]`).value=change;
}
}
const changeAdultTicket = howMany => {
adultTickets = Math.floor(Number(howMany));
calculateValues();
setHtml();
}
const changeStudentTicket = howMany => {
studentTickets = Math.floor(Number(howMany));
calculateValues();
setHtml();
}
const changeMonyGiven = howMany => {
monyGiven = Math.floor(Number(howMany));
calculateValues();
setHtml();
}
document.getElementById("newshow").addEventListener(
"input",
(e)=>{
const inputName = e.target.getAttribute("name");
if(inputName==="ticketOne"){
changeAdultTicket(e.target.value);
}
if(inputName==="ticketTwo"){
changeStudentTicket(e.target.value);
}
if(inputName==="moneyGiven"){
changeMonyGiven(e.target.value);
}
}
)
<form id="newshow" action="required/post/saveTransaction.php" method="post">
<fieldset>
<input type="hidden" name="teamID" value="<?php echo $_SESSION['teamID']; ?>" />
<h4>Amount of Adults</h4>
<input class="form-control" name="ticketOne" type="number" placeholder="0" step="1">
<br />
<h4>Amount of Students</h4>
<input class="form-control" name="ticketTwo" type="number" placeholder="0" step="1">
<br />
<h4>Money Owed</h4>
<input class="form-control" name="totalAmount" readonly="1">
<br />
<h4>Money Given</h4>
<input class="form-control" name="moneyGiven" type="number" required>
<h4>Change due</h4>
<input class="form-control" name="changeDue" readonly="1">
<input type="hidden" name="username" value="<?php echo $_SESSION['username']; ?>" />
<input type="hidden" class="form-control" name="bothTickets" readonly="1">
<input type="hidden" class="form-control" name="base" readonly="1">
<input type="hidden" class="form-control" name="calculation" readonly="1">
</fieldset>
<div class="modal-footer">
<button class="btn btn-default" type="button" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Process" />
</div>
</form>
Related
const roll = $(".roll-btn");
const rollVal = $("#roll-number");
const rollStat = $("#roll-status");
const luckRoll = $("#roll-luck-btn");
const charSheet = $("#char-sheet-container")
const stat = $('.stat')
let result = Math.ceil(Math.random() * 99);
//converts the hidden value of the roll to being seen
rollVal.attr("data-state", "reveal");
if (rollVal.data("data-state", "reveal")) {
rollVal.css("display", "block");
}
//converts the hidden status to being seen
rollStat.attr("data-state", "reveal");
if (rollStat.data("data-state", "reveal")) {
rollStat.css("display", "block");
}
const rollOneHundred = () => {
result = Math.ceil(Math.random() * 99);
if (result) {
rollVal.data("data-state", "reveal");
rollVal.text(result);
}
};
roll.on("click", function () {
let two = stat.val() / 2;
let five = stat.val() / 5;
rollOneHundred();
let status = ['Critical Success', 'Extreme Success', 'Hard Success', 'Success', 'Failure', 'Critical Failure']
if (result >= 99) {
rollStat.text(status[5]);
rollStat.data("data-state", "reveal");
} else if (result > stat.val()) {
rollStat.text(status[4]);
rollStat.data("data-state", "reveal");
} else if (result <= stat.val()) {
rollStat.text(status[3]);
rollStat.data("data-state", "reveal");
} else if (result <= two) {
rollStat.text(status[2]);//won't print
rollStat.data("data-state", "reveal");
} else if (result <= five) {
rollStat.text(status[1]);//won't print
rollStat.data("data-state", "reveal");
return;
} else if (result <= 1) {
rollStat.text(status[0]);//won't print
rollStat.data("data-state", "reveal");
return;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main id="root">
<section id="char-sheet-container">
<h2>Character Sheet</h2>
<h3>Base Characteristics</h3>
<label for="str">Strength</label>
<input type="number" id="str" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="dex">Dexterity</label>
<input type="number" id="dex" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="int">Intelligence</label>
<input type="number" id="int" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="wis">Wisdom</label>
<input type="number" id="wis" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="pow">Power</label>
<input type="number" id="pow" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<h3>Vital Characteristics</h3>
<label for="luck">Luck</label>
<input type="number" id="luck" class="stat"><button type="button" class="roll-btn">Roll</button>
<button type="button" id="roll-luck-btn" data-state="hidden">Roll Luck</button><br>
<label for="con">Constitution</label>
<input type="number" id="con" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="vit">Vitality</label>
<input type="number" id="vit" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="me">Mind's Eye</label>
<input type="number" id="me" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<h3>Skills</h3>
<label for="atmo">Atmosphere</label>
<input type="number" id="atmo" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="not">Notice</label>
<input type="number" id="not" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<br>
<button type="button" id="add-skill">Add A Skill</button><br>
</section>
<section id="results-container">
<h4 data-state="hidden" id="roll-number"></h4>
<h4 data-state="hidden" id="roll-status"></h4>
</section>
</main>
I can't get them to print. Also the only value its doing the calculation for is the one in the first skill out of 11 total as you can see in the html, I want people to be able to roll for each skill individually and be able to change that number dynamically as the game progresses. Any thoughts?
I am using javascript calculation. multiply 2 numbers: number 1 * number 2 = total and how g-total but working only one value display?
I have need number 1 * number 2 = total and show Gtotal so please help and share a valuable idea...
HTML
<input
name="per_hour"
id="per_hour"
class="form-control"
value=""
onblur="perhour()"
placeholder="0"
/>
<input
name="per_hour_x"
id="per_hour_x"
class="form-control"
onblur="perhour()"
value=""
placeholder="0.00"
/>
Total
<input
name="per_hour_total"
id="per_hour_total"
class="form-control"
value=""
placeholder="0.00"
/>
G-Total
<input
type="text"
class="form-control total-fare"
id="total"
disabled
value="<?= $booking->total_fare ?>"
/>
<script>
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$("#per_hour_total").val(totaperhour).toFixed(2); //working
$("#total").val(totalamt).toFixed(2); //not working
}
</script>
It should be $('#per_hour_total').val(totaperhour.toFixed(2)); and not $('#per_hour_total').val(totaperhour).toFixed(2);
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$('#per_hour_total').val(totaperhour.toFixed(2));
$('#total').val(totalamt.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>
total
<input type="text" class="form-control total-fare" disabled id="total" value="">
</div>
<div>
per_hour
<input name="per_hour" id="per_hour" class="form-control" value="" onblur="perhour()" placeholder="0">
</div>
<div>
per_hour_x
<input name="per_hour_x" id="per_hour_x" class="form-control" onblur="perhour()" value="" placeholder="0.00">
</div>
<div>
per_hour_total
<input name="per_hour_total" id="per_hour_total" class="form-control" value="" placeholder="0.00">
</div>
I am trying to validate HTML form. check a field with two other relative range fields. I want to check all variables isset and between the range before submitting form.
I tried this method not giving the expected result.
How can I do it with other easiest method.
$("#form").submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
var apple = $('.apple').val();
var aFirst = $('.aFirst').val();
var aLast = $('.aLast').val();
var banana = $('.banana').val();
var bFirst = $('.bFirst').val();
var bLast = $('.bLast').val();
var orange = $('.orange').val();
var oFirst = $('.oFirst').val();
var oLast = $('.oLast').val();
if(apple >= aFirst && apple <= aLast){
var a = 'true';
}else{
var a = 'false';
}
if(banana >= bFirst && banana <= bLast){
var b = 'true';
}else{
var b = 'false';
}
if(orange >= oFirst && orange <= oLast){
var o = 'true';
}else{
var o = 'false';
}
if(a == 'true' && b == 'true' && o == 'true')
{
alert('success');
//do ajax
}else{
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Apple Price:</label>
<input type="number" class="apple" placeholder="Type between 15-25">
<input type="hidden" class="aFirst" value="10">
<input type="hidden" class="aLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>
The hidden input classes for apples should be aFirst and aLast:
Update: I have corrected the following line:
<input type="hidden" class="aLast" value="25">
Update 2: Works when fruit divs are removed. + Cleanup.
$("#form").submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var apple = $('.apple').val();
var aFirst = $('.aFirst').val();
var aLast = $('.aLast').val();
var banana = $('.banana').val();
var bFirst = $('.bFirst').val();
var bLast = $('.bLast').val();
var orange = $('.orange').val();
var oFirst = $('.oFirst').val();
var oLast = $('.oLast').val();
var a = true;
var b = true;
var o = true;
if (apple == "" || apple < aFirst || apple > aLast) {
a = false;
}
if (banana == "" || banana < bFirst || banana > bLast) {
b = false;
}
if (orange == "" || orange < oFirst || orange > oLast) {
o = false;
}
if (a && b && o) {
alert('success');
//do ajax
} else {
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>
There is a typo,
you have a class name as qFirst and qLast in HTML and js you have written .aFirst and .aLast.
Also convert all values to Number.
When you do .val(), it returns string. And Comparing Strings can give unexpected results
$("#form").submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
var apple = Number($('.apple').val());
var aFirst = Number($('.aFirst').val());
var aLast = Number($('.aLast').val());
var banana = Number($('.banana').val());
var bFirst = Number($('.bFirst').val());
var bLast = Number($('.bLast').val());
var orange = Number($('.orange').val());
var oFirst = Number($('.oFirst').val());
var oLast = Number($('.oLast').val());
if(apple >= aFirst && apple <= aLast){
var a = 'true';
}else{
var a = 'false';
}
if(banana >= bFirst && banana <= bLast){
var b = 'true';
}else{
var b = 'false';
}
if(orange >= oFirst && orange <= oLast){
var o = 'true';
}else{
var o = 'false';
}
if(a == 'true' && b == 'true' && o == 'true')
{
alert('success');
//do ajax
}else{
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Apple Price:</label>
<input type="number" class="apple" placeholder="Type between 15-25">
<input type="hidden" class="aFirst" value="10">
<input type="hidden" class="aLast" value="25">
</div>
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>
I am doing a simple online form to calculate BMR using Harris–Benedict equation with the imperial measurements. I don't know where the error is inside my code but right now only the Clear the form button works. I didn't post the entire HTML code for the webpage because it looks just like I want it and it's only the calculation that I am having the problem with.
<form>
<fieldset id="ImpCalcInfo">
<label for="ageinput">
Age
<input tabindex="1" type="text" id="ageinput" name="age" />
</label>
<label for="heightinput">
Height
<input tabindex="3" type="text" id="heightinput" name="heigh" />
</label>
<label for="weightinput">
Weight
<input tabindex="5" type="text" id="weightinput" name="weight" />
</label>
<label for="genderinput">
<input name="gender" tabindex="7" type="radio" id="maleinput" value="1" checked>Male
<input name="gender" tabindex="9" type="radio" id="femaleinput" value="0">Female
</label>
</fieldset>
<input tabindex="11" type="button" id="submit" value="Submit" />
<input tabindex="13" type="reset" value="Clear fields" />
</form>
function impCalc() {
var bmrIm = 0;
var ageIm = document.getElementById("ageinput").value;
var heightIm = document.getElementById("heightinput").value;
var weightIm = document.getElementById("weightinput").value;
var genderIm = document.getElementById("gender").value;
if (genderIm.value = "1") {
bmrIm = 66 + (6.2 * weightIm) + (12.7 * heightIm) - (6.76 * ageIm);
}
else {
bmrIm = 655 + (4.35 * weightIm) + (4.7 * heightIm) - (4.7 * ageIm);
}
(ageIm && heightIm && weightIm) ? alert("Your BMR is: " + bmrIm) : alert("Please fill in all fields");
}
document.getElementById("button").addEventListener("submit", impCalc, false);
The radio button were not working because you were taking them as an ID but the id does not exist in the input. You have get them via getElementsByName()[0]
Also you event listener did not know where button is clicked so the button id is is unique and it will listen to that click only when you click submit.
Here is working demo: https://jsfiddle.net/usmanmunir/tjsnaz4w/10/
function impCalc() {
var bmrIm = 0;
var ageIm = document.getElementById("ageinput").value;
var heightIm = document.getElementById("heightinput").value;
var weightIm = document.getElementById("weightinput").value;
var genderIm = document.getElementsByName("gender")[0].value
if (genderIm.value == "1") {
bmrIm = 66 + (6.2 * weightIm) + (12.7 * heightIm) - (6.76 * ageIm);
}
else {
bmrIm = 655 + (4.35 * weightIm) + (4.7 * heightIm) - (4.7 * ageIm);
}
(ageIm && heightIm && weightIm) ? alert("Your BMR is: " + bmrIm) : alert("Please fill in all fields");
}
var el = document.getElementById('submit');
el.addEventListener("click", impCalc, false);
HTML
<form>
<fieldset id="ImpCalcInfo">
<label for="ageinput">
Age
<input tabindex="1" type="text" id="ageinput" name="age" />
</label>
<label for="heightinput">
Height
<input tabindex="3" type="text" id="heightinput" name="heigh" />
</label>
<label for="weightinput">
Weight
<input tabindex="5" type="text" id="weightinput" name="weight" />
</label>
<label for="genderinput">
<input name="gender" tabindex="7" type="radio" id="gender" value="1" checked>Male
<input name="gender" tabindex="9" type="radio" id="gender" value="0">Female
</label>
</fieldset>
<input tabindex="11" type="button" id="submit" value="Submit" />
<input tabindex="13" type="reset" value="Clear fields" />
</form>
Hope this helps.
I want to clear form when the radio button is changed. Example gender is male and I fill number in weight input only If I change gender, the form will be clear or when I fill number in all input and click calculate and then BMR show me If I change gender, the form will be clear too.
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', toBmr);
});
const toBmr = () => {
const gender = document.querySelector('[name=gender]:checked').value;
let weight = +document.getElementById('weight').value;
let height = +document.getElementById('height').value;
let age = +document.getElementById('age').value;
if (weight && age && height) {
let result = (10 * weight) + (6.25 * height) - (5 * age)
result += gender === 'male' ? 5 : -161;
document.getElementById('result').innerHTML = result.toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
const clearForm = () => {
document.getElementById('do-form').reset();
document.getElementById('showResult').style.display = "none";
}
const changeGender = () => {
let form = toBmr();
let r = document.getElementById('showResult').style.display;
if (r == "block") {
form = document.querySelector('[name=gender]:checked').addEventListener('change', clearForm());
}
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<div id="selectGender" onchange="changeGender()">
<p>Gender:
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</p>
</div>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
use form.reset() and then check the button
clearForm = (el) => {
document.querySelector("#f1").reset(); // reset the form
el.checked = true; // since we passed the element into the function we can simply check it
}
<form id="f1">
<input type="text" name="t" /><br />
<input type="radio" id="b1" name="b" value="b1" onclick="clearForm(this)" />
<label for="b1">b1</label><br>
<input type="radio" id="b2" name="b" value="b2" onclick="clearForm(this)" />
<label for="b2">b2</label><br>
</form>