Controlling user date picking based on two different values - javascript

I have this case:
two datepickers,and two values, and a select (HTML terms).
Select Start
<input type="date" name ="datepicker_start" id="datepicker" value="" class="datepicker" size="20" />
<br>
Select End
<input type="date" name ="datepicker_end" id="datepicker2" value="" class="datepicker" size="20" />
<br>
Balance 1
<input type="number" name="tleave" id="Total" value="20" readonly="true" size="10" />
<br>
Balance 2
<input type="number" name="tleave2" id="Total2" value="2" readonly="true" size="10" />
<br>
<select onchange="checkdate();" name="LeaveType">
<option value="0"> select balance</option>
<option value="1"> Balance 1</option>
<option value="2"> Balance 2</option>
<option value="3"> Balance 3</option>
</select>
I started putting up a code that checks the input dates and compare it to a value depending on the selection of select option.
function checkdate() {
var start = new Date( $('#datepicker').val() ).getTime(),
end = new Date( $('#datepicker2').val() ).getTime();
diff = ((end - start) / 86400000) ;
//1000 * 60 * 60 * 24 = 1 day = 86400000
if ($('#element option[value="1"]').attr("selected", "selected"))
{
if( diff > $('#Total').val())
{
alert( diff+ " days of balance 1 more than the available" );
}
}
if ($('#element option[value="2"]').attr("selected", "selected"))
{
if( diff > $('#Total2').val())
{
alert( diff+ " days of balance 2 more than the available" );
}
}
};
I.E. let consider that the user have two different balances,so after he selects the duration,based on which balance type he wants,the function should returns a pop-up if the balance is less the requested.
the current issue is that : the function is not separating on changing option.(you will understand better if you check the code below)
or here's my JSFiddle

You could make a shorter version of your code if you change the id of #Total to #Total1 and use this:
function checkdate() {
var start = new Date( $('#datepicker').val() ).getTime(),
end = new Date( $('#datepicker2').val() ).getTime();
var diff = ((end - start) / 86400000) ;
var val = $('#LeaveType').val();
if( diff > $('#Total'+val).val()){
alert( diff+ " days of balance "+val+" more than the available" );
}
};

I managed to fixed it.
I added ID to the select
<select onchange="checkdate();" name="LeaveType" id="LeaveType">
the issue was on these lines :
if ($('#element option[value="1"]').attr("selected", "selected"))
and
if ($('#element option[value="2"]').attr("selected", "selected"))
i changed them to:
var option = document.getElementById("LeaveType").value;
if (option =='1')
AND
if (option =='2')
Now function is working great.
Thank you..

Related

JS time calculation add and set value

I'm making a page to easily calculate when I could go home from work. The page should set a start date when loaded. That way I don't have to know when I started working and just open my browser. Then by clicking one of the buttons it should just add some hours.
The example is one of the many things I've tried already. But this one is close I think. Any suggestions are welcome. I didn't include jquery because of the small scale this has.
function reset() {
var date = new Date();
var hour = date.getHours(),
min = date.getMinutes();
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;
var timestamp = hour + ":" + min;
document.getElementById("start_time").value = timestamp;
}
function add_time_76() {
var start = document.getElementById("start_time").value;
document.getElementById("end_time").value = start + 7, 6;
}
function getTotal() {
var start = document.getElementById("start_time").value;
var end = document.getElementById("end_time").value;
document.getElementById("total").value = end - start;
}
<body onload="reset()">
<p>Start time: <input name="start_time" type="time" /></p>
<p>Time to go home: <input name="end_time" type="time" /></p>
<p>Total hours: <input type="text" name="total" readonly></p>
<button onclick="add_time_76()">Add 7,6h</button>
<button onclick="add_time_8()">Add 8h</button>
<br><br>
<button onclick="getTotal()">Calculate Total</button>
<br><br>
<button onclick="reset()">Reset</button>
</body>
The time fields aren't getting populated when I want them to be.
Just add a id to your inputs.
<p>Start time: <input id="start_time" name="start_time" type="time" /></p>
<p>Time to go home: <input id="end_time" name="end_time" type="time" /></p>
<p>Total hours: <input id="total" type="text" name="total" readonly></p>

how can i fix my javascript calculation which is not working?

the problem is the "total price" is not working.when i pick the "pickup date" and "drop date" it will show the value in the input form. i have to key in the number in "number of days" then the total price will calculate. i need the "total of price" is auto calculate. i have try various event of javascript. here i will attach my code. hope someone will help me. thanks in advance.
function sum() {
var txtFirstNumberValue = document.getElementById('num1').value;
var txtSecondNumberValue = document.getElementById('numdays2').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('num3').value = result;
}
}
function GetDays() {
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("drop_date")) {
document.getElementById("numdays2").value = GetDays();
}
}
<label for="total">Price per day:</label>
<input type="text" name="price" id="num1" onkeyup="sum();" value="3" readonly>
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" onchange="cal()" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" onchange="cal()" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<input type="text" id="numdays2" name="numdays" oninput="sum();" />
<label for="total">Total Price (RM)</label>
<input type="text" name="test" placeholder="Total Price" value="" id="num3">
i expect that the total price can automatically calculate.
You just need to make sure your sum function (or in the example just cal) is being called when your inputs are complete and valid. Since you may want to restrict the user from manually setting the number of days I've demonstrated how you might do this by firing a change event programmatically. It's also current practice to attach events to elements programmatically instead of using the inline HTML5 event notation (e.g. "onchange=foo"), see Why are inline event handler attributes a bad idea in modern semantic HTML?
function setDate(event) {
var days = getDays();
// if the number of days is valid
if (!isNaN(days)) {
var nod = document.getElementById("numdays2");
nod.value = days;
// programmatically setting a value will not fire a change event
nod.dispatchEvent(new Event("change"));
}
}
function getDays() {
// returns NaN if either date does not hold a valid date
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
var pricePerDay = document.getElementById("pricePerDay").value;
if (0 == (pricePerDay = parseInt(pricePerDay))) { return } // TODO needs to handle decimal values
document.getElementById("total").value = parseInt(document.getElementById("numdays2").value) * pricePerDay;
}
function init() {
document.getElementById("drop_date").addEventListener("change", setDate);
document.getElementById("pick_date").addEventListener("change", setDate);
document.getElementById("numdays2").addEventListener("change", cal);
}
document.addEventListener("DOMContentLoaded", init);
<label for="total">Price per day:</label>
<input type="text" name="price" id="pricePerDay" value="" placeholder="Manually enter a value">
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<!-- numdays2 is readonly to ensure the date pickers are used -->
<input type="text" id="numdays2" name="numdays" readonly placeholder="Select dates above" />
<label for="total">Total Price (RM)</label>
<input id="total" type="text" readonly name="test" placeholder="Total Price" value="" id="num3">
</div>
</div>

Dynamic textbox that calculates price based on change in quantity or item

I'm new to javascript and am keen on learning.
I currently have a form that allows the user to select their food, enter their quantity and calculates the price.
My function is able to dynamically calculate the price whenever i change the food item selected. However, if i choose re-enter another quantity, the price will not update dynamically. I'm trying make it so that the price will dyanmically update whenever i change either the food dropdown or the quantity value. Appreciate any kind help.
Thank you.
Attached is my code.
function getSelectValue() {
var selectedValue1 = document.getElementById("dropdownList").value;
if (selectedValue1 === 'Carbonara') {
var currentPrice1 = 4.50 * parseFloat(amount_1.value);
document.getElementById("price_1").value = "$" + currentPrice1;
} else {
var currentPrice1 = 3.50 * parseFloat(amount_1.value);
document.getElementById("price_1").value = "$" + currentPrice1;
}
var selectedValue2 = document.getElementById("dropdownList2").value;
if (selectedValue2 === 'Carbonara') {
document.getElementById("price_2").value = "4.50";
var currentPrice2 = 4.50 * parseFloat(amount_2.value);
document.getElementById("price_2").value = "$" + currentPrice1;
} else {
var currentPrice2 = 3.50 * parseFloat(amount_2.value);
document.getElementById("price_2").value = "3.50";
}
}
Select Food:
<select id="dropdownList" name="dropdownList" onchange="getSelectValue();">
<option value="Prawn Aglio Olio">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="text" id="amount_1">
<br>
Price per unit:
<input type="text" id="price_1" value="" disabled>
<br>
<br>
<!-- Second Selection -->
Select Food:
<select id="dropdownList2" name="dropdownList2" onchange="getSelectValue();">
<option value="">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="text" id="amount_2">
<br>
Price per unit:
<input type="text" id="price_2" value="" disabled>
<br>
<input type ="button" value="Submit">
<a href="vendor.jsp">
<input type="button" value="Back">
</a>
</form>
Try to write the same event (getSelectedValue()) in the input of quantity
Try to initialize all the variables at the beginning so that everything is cleaner
Check that the input element.value "Quanity" exists, if so, fill in the field of 'price'
Test this
function getSelectValue() {
var dropdownList = document.getElementById("dropdownList");
var price_1 = document.getElementById("price_1")
var amount_1 = document.getElementById("amount_1");
var dropdownList2 = document.getElementById("dropdownList2");
var price_2 = document.getElementById("price_2");
var amount_2 = document.getElementById("amount_2");
var currentPrice1 = "$" + 0;
var currentPrice2 = "$" + 0;
if (amount_1.value) {
if (dropdownList.value === 'Carbonara') {
currentPrice1 = 4.50 * parseFloat(amount_1.value);
} else {
currentPrice1 = 3.50 * parseFloat(amount_1.value);
}
price_1.value = "$" + currentPrice1;
}
if (amount_2.value) {
if (dropdownList2.value === 'Carbonara') {
currentPrice2 = 4.50 * parseFloat(amount_2.value);
} else {
currentPrice2 = 3.50 * parseFloat(amount_2.value);
}
price_2.value = "$" + currentPrice2;
}
}
Select Food:
<select id="dropdownList" name="dropdownList" onchange="getSelectValue();">
<option value="Prawn Aglio Olio">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="number" id="amount_1" onchange="getSelectValue();">
<br>
Price per unit:
<input type="text" id="price_1" value="" disabled>
<br>
<br>
<!-- Second Selection -->
Select Food:
<select id="dropdownList2" name="dropdownList2" onchange="getSelectValue();">
<option value="">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="number" id="amount_2" onchange="getSelectValue();">
<br>
Price per unit:
<input type="text" id="price_2" value="" disabled>
<br>
<input type ="button" value="Submit">
<a href="vendor.jsp">
<input type="button" value="Back">
</a>
</form>

Calculate the values of input where each input has different prices. Any shorter code for this?(javascript only)

The code below is working fine but what if there are 100 inputs? any shorter way to do this?
function checkTotal() {
var a = document.getElementById("sandwich").value;
var b = document.getElementById("burger").value;
var c = document.getElementById("cake").value;
var d = document.getElementById("coffee").value;
document.getElementById("total").value = parseInt(a) * 10 + parseInt(b) * 5 + parseInt(c) * 15 + parseInt(d) * 20;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input type="number" id="sandwich" value="0" onkeyup="checkTotal()"><br>
<label>Burger</label>
<input type="number" id="burger" value="0" onkeyup="checkTotal()"><br>
<label>Cake</label>
<input type="number" id="cake" value="0" onkeyup="checkTotal()"><br>
<label>Coffee</label>
<input type="number" id="coffee" value="0" onkeyup="checkTotal()"><br> Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
1) Here each input article has a different price.
2) The value of the input should be mutiply with its price given(Eg. if the sandwich has a price:30, and user inputs value 2 it should calculte the total=price*input value.)
3) i have my code which is working fine but is the above code is the right way to do?
4) what if there are 100 of article inputs. is there shorter code or should i create variable for each one?
what if there are 100 of article inputs. is there shorter code or
should i create variable for each one?
You can maintain a map
var idPriceMap = {
"sandwich" : 20,
"burger" : 10,
"cake" : 5,
"coffee" : 10
};
You can iterate this and produce your value using reduce
var output = Object.keys( idPriceMap ).reduce( function(a,b){
var value = +document.getElementById( b ).value;
a += value * idPriceMap[ b ];
return a;
}, 0);
document.getElementById( "total" ).value = output;
Another way to try is to give your elements a class and some data attributes that can be retrieved by JavaScript using dataset. You can then use them to make your calculations. That way you get rid of ids and you just have to change the HTML code to add a new element.
function checkTotal() {
var total = 0,
foods = document.querySelectorAll('.food');
for (var i = 0; i < foods.length; i++) {
var food = foods[i],
name = food.dataset.item,
price = parseInt(food.dataset.price),
howMany = parseInt(food.value);
console.log(howMany, name, 'costs', (howMany * price));
total += howMany * price;
}
document.getElementById('total').value = total;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input class="food" data-item="sandwich" data-price="30" type="number" value="0" onBlur="checkTotal()"><br>
<label>Burger</label>
<input class="food" data-item="burger" data-price="10" type="number" value="0" onBlur="checkTotal()"><br>
<label>Cake</label>
<input class="food" data-item="cake" data-price="5" type="number" value="0" onBlur="checkTotal()"><br>
<label>Coffee</label>
<input class="food" data-item="coffee" data-price="15" type="number" value="0" onBlur="checkTotal()"><br>
Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
As a side note, you should give a try on Angular or Knockout which can help you to achieve those operations.

Loan Calculator (jQuery) not working right

I have a loan calculator that I have built using JQuery, HTML, and CSS. It functions ok. The weird thing is I have to refresh the page in order to get it to calculate correctly. I'm not sure what I'm doing (or not doing) correctly. Would love some feedback.
$(document).ready(function() {
// variables
var amount = $('#loanAmount').val();
var yearlyInterestRate = .12;
var monthlyInterestRate = yearlyInterestRate / 12;
var twelveMon = 12;
var eighteenMon = 18;
var twentyFourMon = 24;
var duration = $('input[name=duration]:checked').val();
var calcButton = $('.calculate');
var resetButton = $('.reset');
var monthPay;
$('.results').addClass('hidden');
// Calculate Monthly Payment
calcButton.click(function(event) {
event.preventDefault();
monthPay = (monthlyInterestRate * amount) / [1 - Math.pow((1 + monthlyInterestRate), -duration)];
$('.durationValue').text(duration);
$('.monthlyPayment').text(Math.round(monthPay));
$('.results').removeClass('hidden');
});
resetButton.click(function() {
$(form).reset();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<section id="loan-calc">
<form id="calculator">
<input type="text" name="loanAmount" id="loanAmount" placeholder="Loan Amount"><br>
<label>Choose your payment duration:</label><br>
<input type="radio" name="duration" value="12" class="duration"> 12 Months<br>
<input type="radio" name="duration" value="18" class="duration"> 18 Months<br>
<input type="radio" name="duration" value="24" class="duration"> 24 Months <br>
<button class="calculate">Calculate</button>
<!-- <button class="rest">Reset</button>-->
</form>
<p class="results">You chose a duration of <span class="durationValue"></span> months and your monthly payment is $<span class="monthlyPayment"></span> at a 12% yearly interest rate.</p>
</section>
You're setting values on document.ready() - so it's even before any of examples in radio will be clicked. Move getting you values into the .click() function
And it's even more efficient to switch from deprecated .click() method to .on('click', function(){}) just in case you'll expand your form in the future
You need to put the vars inside the function that uses them
PS: In a form an input type="reset" /> will reset the form without needing script
$(document).ready(function() {
$('.results').addClass('hidden');
var yearlyInterestRate = .12;
var monthlyInterestRate = yearlyInterestRate / 12;
var twelveMon = 12;
var eighteenMon = 18;
var twentyFourMon = 24;
// Calculate Monthly Payment
$('.calculate').on("click", function(event) {
event.preventDefault();
var amount = $('#loanAmount').val();
var duration = $('input[name=duration]:checked').val();
var monthPay = (monthlyInterestRate * amount) / [1 - Math.pow((1 + monthlyInterestRate), -duration)];
$('.durationValue').text(duration);
$('.monthlyPayment').text(Math.round(monthPay));
$('.results').removeClass('hidden');
});
$('.reset').on("click", function() {
$(form).reset();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<section id="loan-calc">
<form id="calculator">
<input type="text" name="loanAmount" id="loanAmount" placeholder="Loan Amount"><br>
<label>Choose your payment duration:</label><br>
<input type="radio" name="duration" value="12" class="duration"> 12 Months<br>
<input type="radio" name="duration" value="18" class="duration"> 18 Months<br>
<input type="radio" name="duration" value="24" class="duration"> 24 Months <br>
<button class="calculate">Calculate</button>
<!-- <button class="rest">Reset</button>-->
</form>
<p class="results">You chose a duration of <span class="durationValue"></span> months and your monthly payment is $<span class="monthlyPayment"></span> at a 12% yearly interest rate.</p>
</section>
you take the values of duration and amount on pageload (document ready). if you update the values by filling them in, the variables won't get updated.
move var amount = $('#loanAmount').val(); and var duration = $('input[name=duration]:checked').val(); into the 'onClick' handler so that the amount and duration get updated once you click.

Categories