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.
Related
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>
My first post, so go easy on me!
I'm very new to programming, and I'm making a browser based application that will track arriving flights (I'm an aircraft mechanic by day) and use the .effect("highlight") to make elements flash when the arrival time is near. This will be displayed on a big monitor in our ready room.
Not all of the code is in it's final stages. Some of it is still set up just to test whether or not functions work, like the pulseRed and pulseYellow functions below. I've only tested this in chrome, and only intend it to run in chrome for now, so no guarantees that it will work properly in other browsers.
Here's my issue...
Each new timer that is created is a new div with a unique ID. Each div contains several span elements that are used to display the info on the monitor and store the data.
If you run this code, the block that is marked # problem area # should alert the value of arrivalHour, and it does! Success!... sort of.The problem is that after the first timer, each time the function fires it jams ALL of the arrivalHour values into one window. So if 3 timers had values of 05, 08, and 12, it would display 050812, and it would do it 3 times due to the window popping up once per timer in the loop. What I'm trying to do is have each window display the info from that ONE span element in the div. I'm assuming I need to index which element of the loop I'm on, but I'm fairly stumped as to where the [z] index should go (if that's even the fix here). Once I can pull single values out of those spans, I can set up the rest of the loops and statements to handle the data and I'm basically done.
WHEW! Long explanation, but I wanted to make sure my question made sense.
$(document).ready(function() {
var i = 01; //variable for iterating ID's for each timer below
$("#startButton").fadeTo("fast",0.5);
$("#startButton").mouseenter(function() {
$("#startButton").fadeTo("slow",1);
});
$("#startButton").mouseleave(function() {
$("#startButton").fadeTo("slow",0.5);
});
// pulse function causes the called object to blink red 3 times.
var pulseRed = function() {
$(".timers").effect("highlight", {color: 'red'}).fadeIn();
$(".timers").effect("highlight", {color: 'red'}).fadeIn();
$(".timers").effect("highlight", {color: 'red'}).fadeIn();
}
// pulse function to blink the target div yellow - currently pulses ALL div's for testing
var pulseYellow = function() {
$(".timers").effect("highlight").fadeIn();
$(".timers").effect("highlight").fadeIn();
$(".timers").effect("highlight").fadeIn();
}
setInterval(function(){ //set up just for testing purposes
pulseYellow();
pulseRed();
for (var z = 1; z <= ($(".timers").length); z++) {
alert($('div.timers span.arrivalHour').text()); //<---PROBLEM AREA!!!!!
}
},5000);
//time data formatting for proper display
var d = new Date();
var currentHours = function() {
var hourCheck = d.getHours();
if (hourCheck <= 9) {
return("0" + hourCheck);
}
else {
return(hourCheck);
}
};
var currentMinutes = function() {
var minCheck = d.getMinutes();
if (minCheck <= 9) {
return("0" + minCheck);
}
else {
return(minCheck);
}
};
//button to create the new timer and related functions.
$("#startButton").click(function() {
var tailNumber = $("#tail").val();
var borderColor = $("#colorPicker").val();
var alertTime = $("#alert").val();
var arrHour = $("#hour").val();
var arrMinute = $("#minute").val();
var remarks = $("#discrepancy").val();
// example of similar code at http://jsfiddle.net/nick_craver/TTHDQ/
//creates a new div containing all of the user input data, iterates a new ID so that div's can be blinked individually
$("<div />", { "class":"timers", id:"timer"+i})
.append("<span class='tailNumber'>"+tailNumber +' '+"</span><span class='arrivalHour'>"+arrHour+"</span><span>-</span><span class='arrivalMinute'>"+arrMinute+"</span><span class='table'>"+' ' +"</span><span class='remarks' style='margin: 0 auto; text-align: right'>"+remarks+"</span><div class='delete'>DELETE</div></div>")
.appendTo("#main");
$("#timer" + i).css('border', '2px solid ' +borderColor);
i++;
//delete timer DIV's when no longer needed
$(".delete").click(function() {
$(this).closest(".timers").remove();
});
$('#getTail').get(0).reset();
});
});
EDIT: adding HTML
<!DOCTYPE html>
<html>
<head>
<title>Flight Timer</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javascript" src="script.js"></script>
</head>
<body id="main">
<div id="menu">
<form id="getTail" action="">
Flight Tracker<br>
<input id="tail" type="text" name="Tail Number" placeholder="Tail #">
<select id="colorPicker">
<option value="Green">Color</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Orange">Orange</option>
</select>
<select id="alert">
<option value="default">Flash...</option>
<option value="1">1 minute prior</option>
<option value="5">5 minutes prior</option>
<option value="10">10 minutes prior</option>
<option value="15">15 minutes prior</option>
</select>
<input id="hour" type="text" name="hour" placeholder="Hour">
<br>
<input id="minute" type="text" name="minute" placeholder="Minute">
<input id="discrepancy" type="text" name="pirep" placeholder="Discrepancy or action">
</form>
<div id="startButton">
Add Timer
</div>
</body>
</html>
If I understand correctly, you want a separate alert for each timer (specified by $('.timers')). If that is the case, you want to switch that for statement to look like this:
$("div.timers").each(function() {
alert($(this).find('span.arrivalHour').text());
});
The reason why you're getting all of the text combined is that $('div.timers span.arrivalHour') works as a global selection - meaning that it will retrieve all of the matching elements in the page. The code I'm proposing iterates through each timer, retrieving the arrival hour for each one.
Im really new to Java script, so please bear with me. I'm trying to write a script that will return a date with the addition of a user selected number of days. It works fine as far as returning a value (in the variable expDate, however the value is in the long format (i.e. "Wed Jan 02 2013 00:00:00 GMT+0800 (HKT)) . I run into trouble when I try and break it down into different sections using split. Now my output is just blank.
Any help would be greatly appreciated!
Javascript
<script type="text/javascript">
function setExpDate(){
var formDate = document.getElementById('startDate').value;
var number = +document.getElementById('days').value;
var interval = number;
var startDate = new Date(Date.parse(formDate));
var expDate = startDate;
expDate.setDate(startDate.getDate() + interval);
var splitDate = expDate.split(' ');
var monthFomatted = splitDate[1];
var dayFomatted = splitDate[2];
var yearFomatted = splitDate[3];
document.getElementById('total').innerHTML = monthFormatted;
document.getElementById('daysdays').innerHTML = Dateformatted;
};
</script>
</head>
HTML
<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>
</select>
<div id="total"></div> <br/><div id="daysdays"></div>
</body>
</html>
.split() is a String method (that is it works on strings) and you are trying to use it on a Date object.
You'd be better to do
var monthFomatted = expDate.getMonth();
var dayFomatted = expDate.getDay();
var yearFomatted = expDate.getYear();
getMonth(), getDay() and getYear() being methods that can be used on a Date object.
EDIT
Also note that you are setting monthFomatted then accessing monthFormatted which just isn't going to work. Check to make sure that variables are named consistently.
I have set up a function to take care of my metric conversion an it's not so seamless. I would like to convert lbs to kg and kg to lbs. The problem that i am having is using the jquery change function. It's causing the conversion to only happen on a change but sometimes i just want to due back to back conversions from lbs to kg and it gets stuck and convert the lbs to more lbs or kg to more kg. Any help is appreciated. here is my code below
$("#wUnits").change(function () {
var approx = 2.2;
if ($(this).val() == "lbs") {
value = $("#txtWeight").val() / approx;
$('#wValue').val(value.toFixed(2));
} else if ($(this).val() == "kg") {
value = $("#txtWeight").val() * approx;
$('#wValue').val(value.toFixed(2));
} else {
var value = "";
$('#wValue').val(value);
}
});
and below is my markup
<select id="wUnits">
<option value="">--</option>
<option value="lbs">lbs</option>
<option value="kg">kg</option>
</select>
Ideally what i would like to acheive is a seamless transition between conversions using a dropdown.
What I understand is that you want the conversion to happen not just when you change the value of the <select>
I changed your code a little, it's good to cache the variables in this case, also, I separated the function code to a function named conversion that is triggered on both the <select> change and on keyup or change on your #txtWeight input.
EDIT, implementing Jason Sperske's idea, and added an extra <span> with the resulting units, to avoid confusion. It should be:
HTML:
Convert <input type="text" id="txtWeight" />
<select id="wUnits"><br>
<option value="0">--</option>
<option value="0.45359237">lbs</option>
<option value="2.2">kg</option>
</select><br>
Result: <input type="text" id="wValue" /><span id='rUnits'
JS:
var $units = $("#wUnits");
var $wvalue = $('#wValue');
var $txtweight = $("#txtWeight");
var $runits = $('#rUnits');
$units.change(conversion);
$txtweight.on('keyup change',conversion);
function conversion () {
var value = $txtweight.val() * $units.val();
if(value !== 0) {
$wvalue.val(value.toFixed(2));
$runits.text($units.children(':gt(0):not(:selected)').text());
} else {
$wvalue.val("");
$runits.text('');
}
}
JSBin Demo
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;
}