Whether I have implemented modular javaScript with mixins the right way? - javascript

I am learning to write modular based javaScript coding.
I came across mixins while reading javascript patterns.
Hence I am trying to understand modular style javascript and mixins by
implementing in a few examples.
My example has Employee where an employee can be a contractual employee or a
full time employee.
Contractual employee get paid on hourly basis, whereas an full time get monthly salary with benefits.
the code for the above scenario is as follows,
// and employee module which is common
var employeeModule = (function(){
// private variables
var name = "",
address = "",
salary = 0,
module = {};
// publicly available methods
module.calculateSalary = function(unitOfWork,employeeType){
var totalPay = 0, perDayWage = 0;
if(employeeType === "CONTRACTUAL"){
totalPay = unitOfWork * salary;
}
if(employeeType === "FULLTIME"){ // full time employee also get benifits
perDayWage = salary/30;
totalPay = (perDayWage * unitOfWork) + (perDayWage * 8); // 8 days of leaves per month
totalPay += 2300; // monthly allowance for a fulltime employee
}
return totalPay;
}
module.setSalary = function(_salary){
salary = _salary;
}
module.getName = function(){
return name;
}
module.setName = function(_name){
name = _name;
}
module.getAddress = function(){
return address;
}
module.setAddress = function(addr){
address = addr;
}
module.init = init;
return module;
function init(){
name = "Rahul";
salary = 2500;
address = "India";
}
})();
// a contractual employee module
var contractualEmployeeModule = (function(emp){
var noOfHr = 0, // total number of hours worked
payableSalary = 0; // total hourly pay
var module = {};
// number of hours an contractual employee worked
module.setNoOfHrWorked = function(_noOfHr){
noOfHr = _noOfHr;
}
module.getTotalSalary = function(){
payableSalary = emp.calculateSalary(noOfHr,"CONTRACTUAL");
return payableSalary;
}
// salary rate for per hour work
module.setHourlyRate = function(rate){
emp.setSalary(rate);
}
module.setAddress = function(_address){
emp.setAddress(_address);
}
module.setName = function(_name){
emp.setName(_name);
}
module.init = function(){
emp.init();
}
module.getTotalInfo = function(){
var str = "";
str += "Name \""+emp.getName() + "\" " +
"living in \""+ emp.getAddress() +"\""+
" is contractual employee has earned "+this.getTotalSalary();
return str;
}
return module;
})(employeeModule);
// a fulltime employee module
var fulltimeEmployeeModule = (function(emp){
var noOfDays = 0, // number of days employee attended for work
payableSalary = 0; // total monthly salary an employee is eligible to earn
var module = {};
// number of hours an employee worked in a month
module.setNoOfDaysWorked = function(_noOfDays){
noOfDays = _noOfDays;
}
// calculating total monthly salary
// a fulltime employee gets
module.getTotalSalary = function(){
payableSalary = emp.calculateSalary(noOfDays,"FULLTIME");
return payableSalary;
}
// total monthly salary an fulltime employee
// should earn
module.setMonthlySalary = function(salary){
emp.setSalary(salary);
}
module.setAddress = function(_address){
emp.setAddress(_address);
}
module.setName = function(_name){
emp.setName(_name);
}
module.init = function(){
emp.init();
}
module.getTotalInfo = function(){
var str = "";
str += "Name \""+emp.getName() + "\" " +
"living in \""+ emp.getAddress() +"\""+
" is a fulltime employee has earned "+this.getTotalSalary();
return str;
}
return module;
})(employeeModule);
contractualEmployeeModule.setName("John William");
contractualEmployeeModule.setAddress("New York");
contractualEmployeeModule.setHourlyRate(12);
contractualEmployeeModule.setNoOfHrWorked(123);
console.log(contractualEmployeeModule.getTotalInfo());
fulltimeEmployeeModule.setName("Jack Harrison");
fulltimeEmployeeModule.setAddress("Sedney");
fulltimeEmployeeModule.setMonthlySalary(2300);
fulltimeEmployeeModule.setNoOfDaysWorked(25);
console.log(fulltimeEmployeeModule.getTotalInfo());
From the above code you can see that I have kept total salary calculation as part of employee, and respective to setting salary with each of the employee type.
Can you please go though the code and have a look at my approach.
Whether I am able to achieve modularity in my javaScript code.
Also the above way of coding can be done in a different way, if yes can you please give me some example.
The output of the above code is
E:\RahulShivsharan\MyPractise\DesignPatternsInJavaScript\modules>node ex03.js
Name "John William" living in "New York" is contractual employee has earned 1476
Name "Jack Harrison" living in "Sedney" is a full time employee has earned 4830

Related

How to calculate and distribute the result on html?

I have two values on my html: "Money" and "Time", and those values come from Session Storage, depending on what the person filled previously on another html page.
So lets say the person filled that they need to pay $100 in 2 days.
What i'm trying to do, is to create a list, showing the number of payments, with the amount to be paid in each payment. Like the example below
MONEY: $100 /
TIME: 2 Days
RESULT:
$50
$50
So if the person has 5 days, instead of 2, it would appear as:
$20
$20
$20
$20
$20
What i have so far is:
HTML
<p id="money-value"></p>
<p id="time-value"></p>
<div id="payments"></div>
<script>
const displayMoney = document.getElementById("money-value");
const storedMoney = sessionStorage.getItem("Money");
window.addEventListener("load", () => {
displayMoney.innerHTML = "Money: " + storedMoney
});
const displayTime = document.getElementById("time-value");
const storedTime = sessionStorage.getItem("Time");
window.addEventListener("load", () => {
displayTime.innerHTML = "Time: " + storedTime
});
</script>
What i'm trying to do here, is to use Javascript to create a list element, inside the <div id="payments> that would not only calculate the amount to be paid in each payment, but also that the number of "topics" (payments) would increase, according to the number of "time" the person has (Just like the example i gave).
This might be the result you wanted. But I'm pretty sure that there are better ways to program this.
const displayMoney = document.getElementById("money-value");
const storedMoney = 100; //example
window.addEventListener("load", () => {
displayMoney.innerHTML = "Money: " + storedMoney
});
const displayTime = document.getElementById("time-value");
const storedTime = 5;//example
window.addEventListener("load", () => {
displayTime.innerHTML = "Time: " + storedTime
});
var calc = storedMoney / storedTime;
for (let i = 0; i < storedTime; i++) {
var list = document.createElement("li");
list.innerText = `${calc}`;
document.body.appendChild(list);
}
<p id="money-value"></p>
<p id="time-value"></p>
<div id="payments"></div>

Dynamically display sales tax when I select a state?

I am a student working on an assignment. The assignment is to
create an array that lists states
create a parallel array that lists state taxes
use JS to dynamically load the lists of states into the drop down menu
create a function that will display the tax rate using parallel state array...they want us to use a loop
I am stuck on the final part where I create a function using loops that will display the sales tax. My code is below.
let states = ["state1", "state2", "state3", "state4"];
let salesTax = ["6%", "11%", "7%", "8%"];
function displayTax(){
for(x=0; x < states.length; x++){
document.getElementById("displayTaxPercent").innerHTML = salesTax[x];
}
}
When I do this I just get 8% over and over again.
The reason you are getting value as 8% is because you are not giving the selected value and code is simply iterating through all values and hence it will always show last value.
Here is simple example
let states = ["state1", "state2", "state3", "state4"];
let salesTax = ["6%", "11%", "7%", "8%"];
function displayTax(state){
console.log(state + " : " + salesTax[states.indexOf(state)])
//document.getElementById("displayTaxPercent").innerHTML = salesTax[states.indexOf(state)];
}
displayTax("state1");
displayTax("state3");
const stateSelect = document.querySelector("#stateSelect");
let states = ["state1", "state2", "state3", "state4"];
let salesTax = ["6%", "11%", "7%", "8%"];
stateSelect.append(
...states.map((state, stateI) => {
const optionEl = document.createElement("option");
optionEl.value = stateI;
optionEl.innerText = state;
return optionEl;
})
);
const display = () => {
document.querySelector("#results").innerText =
"Sales tax in " +
states[stateSelect.value] +
" is " +
salesTax[stateSelect.value];
};
stateSelect.addEventListener("change", display);
display();
<select id="stateSelect">
</select>
<p id="results"></p>

How can I properly use array for my problem? Javascript

I'm having trouble figuring out on how can I properly use the array of distance that I made. I am creating a simple web app where user is going to select their origin and preferred destination and I need to compute for the ETA. I already can compute for ETA but the code is so long and so I was wondering if there is better way to do this.
for example:
1) in the select options I have 4 locations which is manila,QC, makati and marikina.
2) if the user selected Manila as Origin and QC as the destination I can compute it using only if-else but if I were to consider every possible way my code will be long with if-else statement.
BTW this is just a sample data of select options and the true data consist of 24 locations and destinations. So I'm really hoping I can have an easy way to do this.
I only tried if-else statement and I was thinking maybe I just loop it but I don't how to start.
please see code for reference. Thank you!
console.clear()
function validateSelect(e) {
var origin = e.target.querySelector("[name=origin]").value;
var destination = e.target.querySelector("[name=destination]").value;
if (origin == destination) {
e.stopPropagation()
e.preventDefault()
alert("Origin and Destination can't be the same");
return false;
}
}
var distanceArray = [10000,20000,30000];
//manila to qc 10000 meter
//qc to makati 20000 meter
//makati to marikina 30000 meter
document.getElementById('findEta').addEventListener('submit', validateSelect);//for form find eta
function getEta(){
var selectedOrigin = document.getElementById("origin").selectedIndex;
var selectedDestination = document.getElementById("destination").selectedIndex;
var estimatedTimeOfArrival = document.getElementById("estimatedTimeOfArrival");
if((selectedOrigin == 0)&& (selectedDestination == 1)){
//manila to qc
distance = 10000;
var speed = 5.56; //converted speed from 20km/h
time = distance/speed;
eta = Math.floor(time).toString();
if((eta >=60)){
var newEta = eta /60; //minutes
var mod = eta%60; //seconds
newEta = Math.floor(newEta);
estimatedTimeOfArrival.value = newEta + "m "+mod+"s" ;
}else{
eta.toString();
estimatedTimeOfArrival.value = eta + " s";
}
}else if((selectedOrigin == 0)&& (selectedDestination == 2)){
distance = 20000;
var speed = 5.56;
time = distance/speed;
eta = Math.floor(time).toString();
if((eta >=60)){
var newEta = eta /60; //minutes
var mod = eta%60; //seconds
newEta = Math.floor(newEta);
estimatedTimeOfArrival.value = newEta + "m "+mod+"s" ;
}else{
eta.toString();
estimatedTimeOfArrival.value = eta + " s";
}
}else if((selectedOrigin == 0)&& (selectedDestination == 2)){
distance = 30000;
var speed = 5.56;
time = distance/speed;
eta = Math.floor(time).toString();
if((eta >=60)){
var newEta = eta /60; //minutes
var mod = eta%60; //seconds
newEta = Math.floor(newEta);
estimatedTimeOfArrival.value = newEta + "m "+mod+"s" ;
}else{
eta.toString();
estimatedTimeOfArrival.value = eta + " s";
}
}
}
function alertFunction(){
var selectedOrigin = document.getElementById("origin").value;
var selectedDestination = document.getElementById("destination").value;
var estimatedTimeOfArrival = document.getElementById("estimatedTimeOfArrival");
if((selectedOrigin == "")&&(selectedDestination =="")){
alert("Please select an option first.");
}else if(selectedOrigin == selectedDestination){
validateSelect(e);
}
else{
getEta();
alert("\nYour Origin is: "+selectedOrigin+"\nYour Destination is: "+selectedDestination+"\nYour ETA is: "+estimatedTimeOfArrival.value);
}
}
<form action="" id="findEta">
<select name="origin" id="origin">
<option value="manila">manila</option>
<option value="QC">QC</option>
<option value="makati">Makati</option>
<option value="marikina">marikina</option>
</select>
<select name="destination" id="destination">
<option value="manila">manila</option>
<option value="QC">QC</option>
<option value="makati">Makati</option>
<option value="marikina">marikina</option>
</select>
<input type="hidden" name="estimatedTimeOfArrival"id="estimatedTimeOfArrival">
<button type="submit" value="submit" onclick="alertFunction()">submit</button>
</form>
We can rule out travel from point A to point A (0 distance) and we can assume that the trip from point A to point B is the same distance as the reverse trip. With this, representing places as single letters (a, b, c, d) a matrix of distances can be described compactly like this... (with made-up distance values)
let distances = {
ab: 1000,
ac: 2000,
ad: 3000,
bc: 1500,
bd: 2500,
cd: 1200
}
function distance(from, to) {
let key = [from, to].sort().join('')
return distances[key]
}
console.log(distance('d', 'a'))
console.log(distance('b', 'c'))
If my understanding is correct, your ETA calculation is the same for each, the variables are the origin and destination which together give you the distance.
To simplify your logic, what you can do is store your distances indexed by these in an object or multi-dimensional array e.g.:
const distances = {
0: {
1: 10000,
2: 20000
},
...
}
And then just lookup the distance from there, e.g.:
const distance = distances[selectedOrigin][selectedDestination];
const speed = 5.56;
...
To take this one step further, you could make it easier to read your structure by using the name values directly in your object, e.g.:
const distances = {
manila: {
qc: 10000,
makati: 20000
},
...
}
And then use the values during lookup, e.g.:
const selectedOrigin = document.getElementById("origin").value;
const selectedDestination = document.getElementById("destination").value;
const distance = distances[selectedOrigin][selectedDestination];
const speed = 5.56;
...
I would consider holding all information in a JSON object or similar.
You can then dynamically populate the drop downs based on the object, including dynamically populating the destination drop down based on origin.
As we are populating the destination dynamically based on origin, we can save the lookup by putting the distance directly as the value of the destination options
//Object to hold info
//Adjust distances as required
const origins = {
"manila": {
"name": "Manilla",
"distances": {
"QC": 1000,
"makati": 2000,
"marikina": 3000
}
},
"QC": {
"name": "QC",
"distances": {
"manila": 1000,
"makati": 2000,
"marikina": 3000
}
},
"makati": {
"name": "Makati",
"distances": {
"manila": 2000,
"QC": 2000,
"marikina": 3000
}
},
"marikina": {
"name": "Marikina",
"distances": {
"manila": 3000,
"QC": 3000,
"makati": 3000
}
}
}
let originDD = document.getElementById("origin");
let destinationDD = document.getElementById("destination");
originDD.innerHTML = "<option value=''>Please Select</option>"
//Populate Origins
for (var prop in origins) {
originDD.innerHTML += `<option value=${prop}>${origins[prop].name}</option>`;
}
//Populate Destinations on change
originDD.addEventListener("change", function() {
var thisOrigin = this.value;
destinationDD.innerHTML = "<option value=''>Please Select</option>";
for (var dest in origins[thisOrigin].distances) {
console.log(dest);
console.log(origins[dest])
destinationDD.innerHTML += `<option value=${origins[thisOrigin].distances[dest]}>${origins[dest].name}</option>`
}
});
//Calculate on destination change
destinationDD.addEventListener("change", function() {
var distance = parseInt(this.value, 10);
var speed = 5.56; //converted speed from 20km/h
var time = distance / speed;
var eta = Math.floor(time).toString();
var estimatedTimeOfArrival = document.getElementById("estimatedTimeOfArrival");
console.log(eta)
if ((eta >= 60)) {
var newEta = eta / 60; //minutes
var mod = eta % 60; //seconds
newEta = Math.floor(newEta);
estimatedTimeOfArrival.value = newEta + "m " + mod + "s";
} else {
eta.toString();
estimatedTimeOfArrival.value = eta + " s";
}
document.querySelector("#eta > span").innerHTML = estimatedTimeOfArrival.value;
});
<form action="" id="findEta">
<select name="origin" id="origin">
</select>
<select name="destination" id="destination">
<option value="">Please Select Origin</option>
</select>
<input type="hidden" name="estimatedTimeOfArrival" id="estimatedTimeOfArrival">
<div id="eta">ETA: <span></span></div>
</form>
It looks like what you're after is the Travelling Salesman problem. It's considered a difficult problem to solve, and probably something beyond the scope of a regular Stack Overflow answer, especially if it's going to be 24 cities (not so bad for 4 cities).
A good place to start is the Branch and Bound algorithm, again by no means trivial. Basically given a starting cities, we work out how to branch out to subsequent available cities in such a way with the lowest "cost" (distance or time) till we arrive at the destination city.

Salary Calculation Function in JavaScript not working

From the input on the HTML, the user inputs the employee name and a number of hours they worked. From here on the submit button it takes the information and stores it in the variables so that I can calculate how much their pay was. Now with this also comes the overtime pay. I thought this was on the right track but whenever I go back to my HTML it displays "undefined". Any suggestions?
//Global Variables
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
function paySalary() {
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("results").innerHTML = "Employee Name: " + employeeName + " | Employee Gross Pay: " + salary;
}
//Event Listener to Submit
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", paySalary, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", paySalary);
}
Screenshot of output
Look at the scope of your salary variable, it's defined inside the if-else block. Make your salary variable accessible to document.getElementById() by declaring it in your function like this:
<html>
<script>
function paySalary() {
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("name").innerHTML = "Employee Name: " + employeeName;
document.getElementById("pay").innerHTML = "Employee Gross Pay: " + salary;
}
</script>
<body>
<input id="name" value="Kamesh Dashora"></input>
<input id="hours" value=40></input>
<br>
<span id="pay">0</span>
<br>
<button id="submit" onclick="paySalary()">Submit</button>
<body>
</html>

How to calculate number of room based on number of person in Javascript?

I’m trying to calculate total number of rooms based on the total number of person enter by the user. The maximum number of person cannot exceed 7 person. The type of room will be Twin (2 person per room-adult&child), Double (2 person per room-adult&child), Single (1 person per room) and extra bed. The type of persons will be Adult, Child with bed and child without bed.
For the room calculation, we need to add [(adult + child with bed/2)] to get the room value. By default, the system must place the number of room in twin sharing. The child with bed must be placed in twin room with adult. So, any exceeding odd number, will result in single room.
Example: 4 adult and 1 child; Total 5 person.
Result: 2 twin and 1 single room.
The user can change this result by changing the twin to double or extra bed.
Result: 2 double and 1 extra bed. The extra bed attached to the double room.
I need some help to work this function in JavaScript. So far I managed to do the system calculation but when try to do the changes by manual it caused error in the calculation.
Example: 4 adult and 1 child; Total 5 person.
Default: 2 twin and 1 single room.
User change to 1 twin (at least 1 twin is must because there is one child), Single can be maximum 2 rooms and the balance 1 adult can select 1 extra bed.
I need some help here:
function cal_rooms()
{
var have_extra_bed="<?=$room_have_extra_bed;?>";
var adult = document.getElementById("adult").value;
var childbed = document.getElementById("childbed").value;
var childwbed = document.getElementById("childwbed").value;
document.getElementById("doubleroom").value="0";
//var totals1=(parseInt(adult));
var totals=(parseInt(adult)+parseInt(childbed)+parseInt(childwbed));
if(adult==0)
{
document.getElementById("childbed").disabled=true;
document.getElementById("childwbed").disabled=true;
document.getElementById("childbed").value="0";
document.getElementById("childwbed").value="0";
document.getElementById("totalperson").value="";
}
else
{
document.getElementById("childbed").disabled=false;
document.getElementById("childwbed").disabled=false;
if(totals>7)
{
var newtots=(totals-parseInt(adult));
alert("Cannot exceed 7!");
document.getElementById("adult").value=0;
document.getElementById("childbed").value="0";
document.getElementById("childwbed").value="0";
document.getElementById("totalperson").value="";
}
else
{
document.getElementById("totalperson").value=totals;
///rooms
var numrooms=((parseInt(adult)+parseInt(childbed))/2);
var new_numrooms=Math.ceil(numrooms);
var check_numrooms=(parseInt(new_numrooms)-numrooms);
var single_num=Math.ceil(check_numrooms);
var twin_num=(parseInt(new_numrooms)-parseInt(single_num));
var doubleroom=document.getElementById("doubleroom").value;
var totals_room1=(parseInt(twin_num)+parseInt(doubleroom)+parseInt(single_num));
if(have_extra_bed=="Y")
{
if(parseInt(adult)>=parseInt(childbed))
{
var max_single_can_select=(parseInt(adult)-parseInt(childbed));
document.getElementById("twin").value=twin_num;
document.getElementById("single").value=single_num;
document.getElementById("temp_single").value=single_num;
document.getElementById("def_single").value=single_num;
document.getElementById("max_single").value=max_single_can_select;
document.getElementById("extrabed").value="0";
document.getElementById("totalroom").value=totals_room1;
document.getElementById("totalextra").value="0";
document.getElementById("single").disabled=false;
}
else
{
document.getElementById("twin").value=twin_num;
document.getElementById("extrabed").value=single_num;
document.getElementById("single").value="0";
document.getElementById("temp_single").value="0";
document.getElementById("def_single").value="0";
document.getElementById("max_single").value="0";
var extra_a=document.getElementById("extrabed").value;
var single_a=document.getElementById("single").value;
var twin_a=document.getElementById("twin").value
var doubleroom=document.getElementById("doubleroom").value;
var totals_room1=(parseInt(single_a)+parseInt(twin_a)+parseInt(doubleroom));
document.getElementById("totalroom").value=totals_room1;
document.getElementById("totalextra").value=extra_a;
document.getElementById("single").disabled=true;
}
}
else
{
if(parseInt(adult)>=parseInt(childbed))
{
var max_single_can_select=(parseInt(adult)-parseInt(childbed));
document.getElementById("twin").value=twin_num;
document.getElementById("single").value=single_num;
document.getElementById("temp_single").value=single_num;
document.getElementById("def_single").value=single_num;
document.getElementById("max_single").value=max_single_can_select;
document.getElementById("extrabed").value="0";
document.getElementById("totalroom").value=totals_room1;
document.getElementById("totalextra").value="0";
document.getElementById("single").disabled=false;
document.getElementById("extrabed").disabled=true;
}
else
{
document.getElementById("twin").value=twin_num;
document.getElementById("single").value=single_num;
document.getElementById("temp_single").value=single_num;
document.getElementById("def_single").value=single_num;
document.getElementById("max_single").value="0";
document.getElementById("extrabed").value="0";
document.getElementById("single").disabled=true;
document.getElementById("extrabed").disabled=true;
var extra_a=document.getElementById("extrabed").value;
var single_a=document.getElementById("single").value;
var twin_a=document.getElementById("twin").value
var doubleroom=document.getElementById("doubleroom").value;
var totals_room1=(parseInt(single_a)+parseInt(twin_a)+parseInt(doubleroom));
document.getElementById("totalroom").value=totals_room1;
document.getElementById("totalextra").value=extra_a;
}
}
return surcharge();
}
}
}
function cal_single()
{
///Start single function
var choose_single = document.getElementById("single").value;
var single_pick = document.getElementById("single_pick").value;
var extra_pick = document.getElementById("extra_pick").value;
var checked_for_doubleroom = document.getElementById("temp_double").value;
var checked_for_single = document.getElementById("temp_single").value;
var checked_for_def_single = document.getElementById("def_single").value;
var total_pax_adult = document.getElementById("adult").value;
var total_pax_childbed = document.getElementById("childbed").value;
var total_pax_bed = (parseInt(total_pax_adult)+parseInt(total_pax_childbed));
if (parseInt(total_pax_bed)%2 == 0)
{
////Even Number
//document.getElementById("temp_single").value=choose_single;
var temp_twin = document.getElementById("twin").value;
var temp_double = document.getElementById("temp_double").value;
var temp_single = document.getElementById("temp_single").value;
var temp_extra = document.getElementById("temp_extra").value;
var total_temp = ((parseInt(temp_twin)*2)+(parseInt(temp_double)*2)+parseInt(temp_single)+parseInt(temp_extra));
var new_total_temp = ((parseInt(temp_twin)*2)+(parseInt(temp_double)*2)+parseInt(choose_single)+parseInt(temp_extra));
if(total_temp>total_pax_bed)
{
alert("Total Number of Room Exceed Total number of Pax!");
document.getElementById("single").value=temp_single;
return false;
}
else
{
var def_single=document.getElementById("def_single").value;
var doubleroom=document.getElementById("doubleroom").value;
var single=document.getElementById("single").value;
var adult = document.getElementById("adult").value;
var childbed = document.getElementById("childbed").value;
///rooms
var numrooms=((parseInt(adult)+parseInt(childbed))/2);
var new_numrooms=Math.ceil(numrooms);
var check_numrooms=(parseInt(new_numrooms)-numrooms);
var single_num=Math.ceil(check_numrooms);
var twin_num=(parseInt(new_numrooms)-parseInt(single_num));
var max_sing=document.getElementById("max_single").value;
if(single>max_sing)
{
if(max_sing==0)
{
alert("Single cannot been select");
document.getElementById("single").value=def_single;
return false;
}
else
{
alert("Single cannot exceed "+max_sing);
document.getElementById("single").value=def_single;
return false;
}
}
else
{
if(single==0)
{
return false;
}
else
{
var latest_twin_num=(parseInt(twin_num)-parseInt(single));
var min_twin_sh=childbed;
if(parseInt(latest_twin_num)<=parseInt(min_twin_sh))
{
var new_latest_twin=min_twin_sh;
}
else
{
var new_latest_twin=latest_twin_num;
}
document.getElementById("single").value=single;
document.getElementById("twin").value=new_latest_twin;
document.getElementById("max_single").value=new_latest_twin;
document.getElementById("temp_single").value=single;
document.getElementById("single_pick").value="Y";
var extra_a=document.getElementById("extrabed").value;
var single_a=document.getElementById("single").value;
var twin_a=document.getElementById("twin").value
var doubleroom=document.getElementById("doubleroom").value;
var totals_room1=(parseInt(single_a)+parseInt(twin_a)+parseInt(doubleroom));
document.getElementById("totalroom").value=totals_room1;
document.getElementById("totalextra").value=extra_a;
}
}
document.getElementById("single").disabled=true;
}
}
else
{
try using javsacript function modulus x= y%2 this will give you exact rooms required and if there's a remainder you can add one more room to it.

Categories

Resources