Simple Hotel Booking Form Total Calculation - javascript

I wonder if anyone can help me... Unfortunately I do not have any Javascript knowledge and finding it a bit difficult to understand.
I am working on a Hotel Booking form and this is what I need to do. There is an option to choose the hotel as well as the options for how many nights are required.
There is also a Totals field. This is where I am stuck. Can someone help me with a script or what to do get the Total field to show the total of the formula of nights times choice of hotel?
This would also need to be a value that would be posted with the other values to the php form which in turn sends me the email with the values.
Here is the link to the form I made: https://www.alpinemalta.net/libyabuild2013/bookNow.html
Thank you to anyone that can help me and please excuse my lack of knowledge in this area.
Regards
Chris Brown (Malta)

looking at your form,
1) i think the drop down list for total of nights is redundant (the total of nights is clear from arrival and departure dates)
2) the dates (for having it simpler using it in JavaScript) use numeric values instead of: '11/05/2013(A)' or such.
<select name="ArrivalDate" size="1" id="ArrivalDate">
<option>Please select</option>
<option value="1368399600">13-05-2013</option>
<option value="1368486000">14-05-2013</option>
...
</select>
3) i didn't notice anywhere the price per night? Maybe the list of hotels could also contain some ID (such as h1a,h1b, h2a, h3a, h3b, h3c, ...) instead of the textual option description (of hotel and room)
<select name="hotel_choice" id="hotel5">
<option value="nothing" selected="selected">None Selected</option>
<option value='nothing'>.</option>
<option value="h1a">Corinthia Single Room</option>
<option value="h1b">Corinthia Double Room</option>
<option value='nothing'>.</option>
...
</select>
if you do that then the JavaScript may not be that complicated (asuming you do those changes and don't mind having the price for each hotel visible in the page source):
<script type='text/javascript'>
var prices={nothing:0,h1a:357,h1b:280.50,h2a:380}; //here are your hotel prices
function calculate() {
var days = Math.round( (
document.getElementById('datedepart').value -
document.getElementById('ArrivalDate').value
) / 86400 ); //timestamp is in seconds
document.getElementById('total_cost').value =
days *
prices[ document.getElementById('hotel5').value ];
}
</script>
please note that there aren't any niceties in the code and it's based on the assumption, that the dates are changed to their representative integer values (such as are returned by php function time() ) also it is possible that i made an error in the ID names of your elements
Then what remains is to hook up the "calculate();" javascript function to onchange event of all the controls and you are done.
<select name="hotel_choice" id="hotel5" onchange='calculate();'>
...
</select>
and
<select name="ArrivalDate" size="1" id="ArrivalDate" onchange='calculate();'>
...
</select>
and the same in the departure date selector.
EDIT:
You could use dates in your date selectors, but you would have to parste that string into a number client side using something like:
var dt=Date.parse(document.getElementById('ArrivalDate').value);
But make sure to check supported date formats for this function and also note it returns the number of milliseconds since 1970 so you will have to be dividing by 86400000 instead of 86400
EDIT - check for dates are filled in
function calculate() {
var dd=document.getElementById('datedepart');
var da=document.getElementById('ArrivalDate');
var total=document.getElementById('total_cost');
var hotel=document.getElementById('hotel5');
//no hotel room selected or not depart date set or not arrival date set
//or departing before arrival (nonsense) - set total to ZERO and exit the function
if ( !(dd.value*1) || !(da.value*1) || da.value>dd.value ) {
total.value='0';//you can set it to 'not allowed' also if you wish (instead of '0')
return;
}
var days = Math.round( (
dd.value -
da.value
) / 86400 ); //timestamp is in seconds
var cost = days * prices[ hotel.value ];
if (isNaN(cost))
cost = 0; //or set to "invalid input" - but this line should not be needed at this point
total.value = cost;
}

Related

Change function parameter based select list

I'm using moment + jquery to list year calendar weeks and items, but I've hardcoded this year, so now Current code for hardcoded calendar year works, so now I'm trying to make select list for the years, so user can change 2020, 2021, 2022 years and this showCalendar(2020); is going to update, (I just need a three next years so..), but I'm not quite sure how I can change this showCalendar(); parameter with dropdown select list? Thanks for the help, if someone have any time to check this :)
This is what print calendar based on year that we have hardcoded
function setup(){
showCalendar(2020); // When change this in 2021 it works.
}
function showCalendar(year){
// all (week numbers, days etc...)
In web-view:
<select id="Year" class="">
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
</select>
You wanna get the <select> option, so something like this would work
let sel = document.getElementById('Year');
let lastValue = sel.value
function setup(){
showCalendar(sel.value); // 2020, 2021, or whatever is selected
}
setInterval(() => {
if(sel.value !== lastValue) setup();
//you wanna call setUp everytime the value change
}, 1000)

How to read values from dropdown lists line by line in table

I'm programming an invoice program. I want to calculate prices row by row. I have a table with rows and columns. A single row consists of 6 columns: "product", "description", "unit cost", "quantity", "vat%" and "total price". VATs can be selected from 4 options in dropdown list.
How to read selected values from dropdown list row by row?
My HTML is like this:
<table id="items">
... ...
... ...
<td><form action="dropdown">
<select id="dropdown-vat">
<option value="0">0%</option>
<option value="10">10%</option>
<option value="14">14%</option>
<option value="24" selected>24%</option>
</select>
</form></td>
... ...
... ...
</table>
I did a JS function like this but it works properly only on the first line.
function update_price() {
var row = $(this).parents('.item-row');
var e = document.getElementById("dropdown-vat");
var vatUser = e.options[e.selectedIndex].value / 100 +1; // THIS IS THE PROBLEM
vatUser = roundNumber(vatUser,2);
var price = row.find('.cost').val().replace("€","") * row.find('.qty').val() * strUser;
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html(price+"€");
The function works properly on the first line.
The price is calculated "cost" * "qty" * "1 + selected VAT"
For example 10 * 1 * 1.20 = 12. // HERE vat is 20% so 1 + 0.2 = 1.2
The problem appears if user adds a second line.
Then the calculator uses vat from the first line.
If the first line is 10 * 1 * 1.2 = 12,
Then second line works like this: 10 * 1 * 1.0 = 12. Instead of using 0% (1.0), program uses 20% (1.2, from the first line).
EDIT:
Function update_price() is called when user changes a cost (blur), a qty(blur) or a vat(click) value.
Here's how I recently resolved a similar-ish issue - and why you are seeing what you are seeing.....
You get the number from the first line as JS (and, therefore, jQuery) can only have UNIQUE 'ids', so the second line (with the same id) is never read.
To solve it, use a 'combo' of things - namely, use a class for a common listener, then grab the info on a 'change' function.
<select id="dropdown-vat" class="vat">
<option>..... as you have them </option>
</select>
in the script....
$(".vat").change(function() {
var selected = this.selectedOptions[0]);
// now you can get its value, classes, whatever
console.log("value of selected is ", selected.val());
});
There may be more direct ways to get this, though this worked for what I needed.
The point here is that IDs must be unique, so you could also make a unique id for each line, then process the change (similar to what I have shown). If you need the id from that line:
var theIdOfTheSelectedLine = selected.id;
There is likely a lot more to totally answering the question, though this should help you with the main issue (non-unique ids on elements).
You can just use the value of the select element
var e = document.getElementById("dropdown-vat");
e.onchange = function() {
// value of e... this or event.target
console.log(this.value);
console.log(event.target.value);
}
<select id="dropdown-vat">
<option value="0">0%</option>
<option value="10">10%</option>
<option value="14">14%</option>
<option value="24" selected>24%</option>
</select>
EDIT: your question is unclear as we don't know what .item-row is and we can't see what a cost (blur), a qty(blur) is about.
My best guess is that following should work:
First change select to use class: <select class="dropdown-vat">
Then, seeing you use jQuery:
function update_price() {
var row = $(this).parents('.item-row'); // the parent table row???
var vatUser = row.find(".dropdown-vat").val();
// etc
}
For dynamically added elements you should use delegated event handlers. Assuming your table already created when running js code:
$("table#items").on("change", ".dropdown-vat", update_price);

Joined / Connected Dynamic Dropdowns

Greetings Stackoverflow Veterans,
I've been struggling for a little while with a small Input Safety Feature. Essentially, for my website users will get to pick a time they wish to start and end their morning shift.
I have two Select inputs which are populated by a date within a loop. Basically, what I've been trying (In vain) to achieve is that when someone picks a start date from the "Start Time" Dropdown, the "End Time" dropdown then has all values less than the "Start Time", disabled.
I've provided an image below to help explain a little better, and the current code I have as well in relation to how my select is working.
As for any progress on Javascript, there basically is none. Everything I have tried in no way works, and I'm starting to struggle to think of new ideas. I've spent plenty of time trying to find solutions here on StackOverflow but I might be searching with the wrong Keywords.
The start time has been selected on the Left Dropdown, at 07:00, but on the Right Dropdown, anything before 07:00 should now be removed / disabled.
<select id="mondayWorking_MorningStart" class="workInput" >
<?php
$tStart = strtotime($start);
$tEnd = strtotime($end);
$tNow = $tStart;
while($tNow <= $tEnd)
{
echo "<option id='monday_MorningStart' name='mondayMorningStart'>" . date("H:i",$tNow) . "</option>";
$tNow = strtotime('+30 minutes',$tNow);
}
?>
</select>
Thank you for your help,
If you need anything else to offer your help, please let me know!
To populate the second dropdown based on first drop down value, first you have to bind onChange event to first dropdown. It means that when you change the first dropdown and select another option, JavaScript(In our case jquery) will fire an event and run a code.
In that function(code) we get the value of the first dropdown, then clear the options of the second dropdown and refill the content of the second dropdown based on the first dropdown value.
I assumed that the second dropdown max value can be 24:00 and the min value should be equal to first dropdown value + 30 minutes...
I've just added a few options to first select for test. you are loading it with your php code and it makes no difference...
So the code will be like this:
$('#selStart').change(function(){
var arrTimeStart = $(this).val().split(":");
var timeStart = parseInt(arrTimeStart[0] * 60) + parseInt(arrTimeStart[1]);
timeStart = timeStart + 30;
var timeEnd = (24 * 60);
$('#selEnd').find('option').remove();
for (iCnt = timeStart; iCnt <= timeEnd; iCnt = iCnt + 30){
vHour = parseInt(iCnt / 60);
vMin = iCnt % 60;
if(vMin == 0)
vMin = '00';
tmpTime = vHour + ':' + vMin;
$('#selEnd').append('<option value='+tmpTime+'>'+tmpTime+'</option>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Start:
<select id="selStart">
<option value="00:00">00:00</option>
<option value="00:30">00:30</option>
<option value="01:00">01:00</option>
<option value="01:30">01:30</option>
<option value="02:00">02:00</option>
<option value="02:30">02:30</option>
<option value="03:00">03:00</option>
<option value="03:30">03:30</option>
<option value="04:00">04:00</option>
<option value="04:30">04:30</option>
</select>
<br>
End:
<select id="selEnd"></select>

setting html <select> option to be the default value based on current time

I have made a basic punchclock webpage & MySQL database,
only problem is when people accidently clock in instead of out at end of day or vice versa it leaves alot of gaps.
I need some sort of code that defaults "startfinish" value to "Start" before 10:30 and "End" after 14:30 but still allows the user to change the option if they needed to
note really sure where to start and if i should use javascript or php (php is in a seperate file as the "form action")
heres my current html code that needs the option changed:
<select name="startfinish" id="startend" required>
<option selected="selected" disabled selection>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
any help would be greatly appreciated
thanks,
Danial
If you aren't opposed to PHP you could check the current time and compare it against the times you've specified. This will have to go in the file you're working from though, not your action file.
<?php
// Set the default timezone so you don't run into timezone issues
// You can set this to whatever suits your application best
// Full list of supported timezones here: http://php.net/manual/en/timezones.php
date_default_timezone_set('America/Vancouver');
// Compare the current time to the start and end times
// This reads: if current time is before start time, option is selected, otherwise it's not
$start = (strtotime('now') < strtotime('10:30 AM today') ? 'selected="selected"' : '');
// This reads: if current time is after end time, option is selected, otherwise it's not
$end = (strtotime('now') > strtotime(' 2:30 PM today') ? 'selected="selected"' : '');
?>
To use this in your select control, you'd echo the variables (shown in shorthand for brevity) in the options. If the date calculations are correct, that option will be selected, otherwise it will remain unchanged. I removed the selection from the placeholder because this setup will ensure Start or End are always selected.
<select name="startfinish" id="startend" required>
<option disabled selection>Please select</option>
<option <?=$start?> value="Start">Start</option>
<option <?=$end?> value="End">End</option>
</select>
The benefit of using PHP in this case is that it runs server-side instead of client-side, so you don't have to worry about the user disabling Javascript and ruining your form design. Though, if you're already depending on jQuery in your application that's probably a non-issue.
You can use the Date object and a bit of jQuery to get the result you're after: http://jsfiddle.net/8cuL0k3h/
$(function() {
// Grab the date object and get hours/minutes
var current = new Date();
var hours = current.getHours();
var minutes = current.getMinutes();
// Check if time is before 10:30am
if( hours <= 10 && minutes < 30 ) {
$('#startend').val('Start');
}
// Check if time is after 2:30pm
else if( hours >= 14 && minutes > 30 ) {
$('#startend').val('End');
}
});
I'm assuming the site is statically generated, in which case PHP wont get a bite of this particular apple. Here's a JS only approach.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
initSelectElement();
}
function makeItemSelected(listElem, index)
{
var i, n = listElem.options.length;
for (i=0; i<n; i++)
{
if (index == i)
listElem.options[i].setAttribute('selected','');
else
listElem.options[i].removeAttribute('selected');
}
}
function initSelectElement()
{
var curTime = new Date();
var curHour = curTime.getHours();
var curMin = curTime.getMinutes();
if ((curMin <= 30) && (curHour <= 10))
{
makeItemSelected(byId('startend'), 1);
}
else if ((curMin >= 30) && (curHour >= 2))
{
makeItemSelected(byId('startend'), 2);
}
}
</script>
<style>
</style>
</head>
<body>
<select name="startfinish" id="startend" required>
<option selected disabled>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
</select>
</body>
</html>

Javascript date returning wrong value

I'm new to Java script and am literally tearing my hair out here. I want a simple date calculator, which updates itself when ever a user changes either a date box or a duration from a drop down menu. I've looked at several ways to do it, and have found one that appears to be quite simple as per below.
It works perfectly if I have 'var interval = 4;' as a fixed value (interval is the duration after the user inputted date). However if I change that line to 'var interval = number;' (the duration input from the select menu), it gives me all kinds of crazy dates(dates which are significantly after the interval), and I don't know why
Is anyone able to help? Thanks in advance
<script type="text/javascript">
function setExpDate(){
var formDate = document.getElementById('startDate').value;
var number = document.getElementById('days').value;
// set number of days to add
var interval = 4;
var startDate = new Date(Date.parse(formDate));
var expDate = startDate;
expDate.setDate(startDate.getDate() + interval);
document.getElementById('total').innerHTML = expDate;
document.getElementById('daysdays').innerHTML = interval;
};
</script>
</head>
<body>
<input type="text" size="10" maxlength="10" id="startDate" name="startDate" onblur="setExpDate(this.value)">
<select name="days" id="days" onchange="setExpDate(this.value)">
<option value="01">1</option>
<option value="02">2</option>
<option value="03">3</option>
<option value="04">4</option>
<option value="05">5</option>
<option value="06">6</option>
<option value="07">7</option>
<div id="total"></div> <br/><div id="daysdays"></div>
</body>
</html>
The values of form fields are always strings. You have to force them to be numbers:
var number = +document.getElementById('days').value;
or
var number = parseInt( document.getElementById('days').value, 10 );
(Either one will work; it's up to you.)
If you don't perform that conversion, then the addition step here:
expDate.setDate(startDate.getDate() + interval);
will be carried out as string concatenation.

Categories