Javascript response on same page - javascript

function check(){
var d = new Date();
var date = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var state = document.form1.state.value;
if(state==1){
document.getElementById("expDate").innerHTML = (date + 4) + "/" + month + "/" + year;
}
else if(state==2){
document.getElementById("expDate").innerHTML = (date + 7) + "/" + month + "/" + year;
}
}
<form name="form1" >
<table width="20%">
<tr>
<td>Select State: </td>
<td>
<select name="state">
<option value=1>CANSAS</option>
<option value=2>NEW YORK</option>
</select>
</td>
</tr>
<tr>
<td>Expected Delivered:</td>
<td><p id="expDate"></p>
</td>
</tr>
<td>
</td>
<td>
<input type="submit" name="submit" value="submit" onClick="return check()">
</td>
</tr>
</table>
</form>
I'm creating a postage calculator using HTML and JavaScript. The calculator will calculate the expected delivery date when users select the state option and submit. After the submit, the selected value will be caught by JavaScript and used as to recognize which area of the state is (south, west, else). Eg: cansas, which is west, duration will be 5 days. Then in the same page the expected delivery date will be shown after it calculate by adding the 5 with current date.

You are almost there. Your code actually sets the innerHTML for 'extDate' as well but after that it submits the form and value disappears as form resets.
Only thing that you have to do is to prevent the form to be submitted by returning false.
function check(e) {
// e.preventDefault();
var d = new Date();
var date = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
// document.getElementById("date").innerHTML = date + "/" + month + "/" + year;
var state = document.form1.state.value;
if (state == 1) {
document.getElementById("expDate").innerHTML = (date + 4) + "/" + month + "/" + year;
}
else if (state == 2) {
document.getElementById("expDate").innerHTML = (date + 7) + "/" + month + "/" + year;
}
return false;
}
I have checked the following the code and for 'New York', it returns Expected Delivered:
26/10/2018

Related

select date from datepicker after i want next year date in next field

from date selected by the datepicker in dd-mm--yy format after this i need next year date with -1 day..i.e From:29-07-2016 then To:28-07-2016 like this...please guyz help me..i m sharing my source code
$('#oldDate').on('change', function(e){
var oldDate = new Date(this.value);
$('.datepicker').datepicker({dateFormat:'dd-mm-yy'});
$('#old').html(new Date(oldDate));
oldDate.setDate(oldDate.getDate()-1);
oldDate.setFullYear(oldDate.getFullYear()+1);
var day = ("0" + oldDate.getDate()).slice(-2);
var month = ("0" + (oldDate.getMonth() + 1)).slice(-2);
var today = oldDate.getFullYear()+"-"+(month)+"-"+(day);
// var today = oldDate.(day)+"-"+(month)+"-"+getFullYear();
// alert(today);
$('#new').val(today);
<p class="left">
<label for="from">FROM:</label>
<input type="text" name="from" id="oldDate" class="datepicker"/>
</p>
<p class="pull-right">
<label for="to">TO:</label>
<input type="text" name="to" id="new">
</p>
To achieve expected result, use datepicker and then use on change function to make work
JS:
$('.datepicker').datepicker({
dateFormat: 'dd-mm-yy'
}).datepicker("setDate", "0");
$('#oldDate').click(function() {
$('#oldDate').datepicker('setDate', new Date());
});
$('#oldDate').on('change', function(e) {
console.log(this.value)
var x = this.value;
var from = x.split("-");
var f = new Date(from[2], from[1] - 1, from[0]);
var oldDate = new Date(f);
$('#old').html(new Date(oldDate));
oldDate.setDate(oldDate.getDate() - 1);
oldDate.setFullYear(oldDate.getFullYear() + 1);
console.log(oldDate)
var day = ("0" + oldDate.getDate()).slice(-2);
var month = ("0" + (oldDate.getMonth() + 1)).slice(-2);
var today = (day) + "-" + (month) + "-" + oldDate.getFullYear();
// var today = oldDate.(day)+"-"+(month)+"-"+getFullYear();
// alert(today);
$('#new').val(today);
});
Codepen-http://codepen.io/nagasai/pen/XKBZmN
Check this :
<script type="text/javascript">
var dt = new Date('2016/12/10');
var month = dt.getMonth()+1;
var day = dt.getDate()-1;
var year = dt.getFullYear()+1;
alert(month + '-' + day + '-' + year);
</script>

How to reset drop down if value change?

I'm working on my project where I have three drop down boxes. User can pick Start time, Meeting Length and End time. My function works fine but I'm missing one more thing, so If user select all of three drop downs they will get all end times in last drop down but now I want if they change meeting length or start time, my end time drop box should give them values with the valid records. Current code works fine if they select everything once but if they change start time or meeting length my end time is still the same.
Here is my jsfiddle with the working example:
https://jsfiddle.net/dmilos89/vy0yy7h9/4/
I tried to reset my function with something like this:
$('#meet_leng').on('chnage');
inside of my existing function but that did not help. If anyone knows how I can refresh my function each time after I change values in my start time and meeting length drop downs please let me know.
$(function() {
//This loop populate values fro meeting length dropdown
for (var i = 5; i <= 60; i += 5) {
$('#meet_leng').append('<option value="' + i + '">' + i + ' min' + '</option>')
}
//Populate start time dropdown with values
for (var i = 700; i <= 1700; i += 15) {
var mins = i % 100;
var hours = parseInt(i / 100);
if (mins > 45) {
mins = 0;
hours += 1;
i = hours * 100;
}
var AmPm = " AM";
//set hours 12 to PM
if (hours == 12) {
AmPm = " PM";
}
//format all hours greater than to PM
if (hours > 12) {
hours = hours - 12;
AmPm = " PM";
}
//populate stime with values
$('#stime').append('<option value="' + ('0' + (hours)).slice(-2) + ':' + ('0' + mins).slice(-2) + AmPm + '">' + ('0' + (hours)).slice(-2) + ':' + ('0' + mins).slice(-2) + AmPm + ' </option>')
}
//onChange function set end time based on start time and meeting length
$('#meet_leng').on('change', function() {
if ($('#stime').val() == '0') {
alert('You have to pick start time first.')
} else {
if ($('#meet_leng').val() == '0') {
$('#hideSlots').hide();
} else {
//convert variables for start and end time to new Date
var time1 = new Date();
var time2 = new Date();
//meeting length converts to int
var meetingLength = parseInt($('#meet_leng').val());
//start time split into hours and minutes
var startTime = $('#stime').val();
var startHour = startTime.split(':')[0];
var startMin = startTime.split(':')[1].replace(/AM|PM/gi, '');
//end time split into hours and minutes
var endTime = '05:00 PM';
var endHour = endTime.split(':')[0];
var endMin = endTime.split(':')[1].replace(/AM|PM/gi, '');
//Check if start time is PM and adjust hours to military
if (startTime.indexOf('PM') > -1) {
if (startHour != 12) {
startHour = parseInt(startHour) + 12;
} else {
startHour = parseInt(startHour);
}
}
//Check if end time is PM and adjust hours to military
if (endTime.indexOf('PM') > -1) {
endHour = parseInt(endHour) + 12;
}
//Date API start time set hours and minutes
time1.setHours(parseInt(startHour));
time1.setMinutes(parseInt(startMin));
//Date API end time set hours and minutes
time2.setHours(parseInt(endHour));
time2.setMinutes(parseInt(endMin));
//Adding meeting length to start time
time1.setMinutes(time1.getMinutes() + meetingLength);
//while loop checks for time values and increment end time for meeting interval
while (time1 <= time2) {
var amPm = " AM";
var hourEnd = time1.getHours();
var minEnd = time1.getMinutes();
if (hourEnd >= 12) {
hourEnd = (hourEnd == 12) ? hourEnd : hourEnd - 12;
amPm = " PM";
}
if (hourEnd == 24) {
hourEnd = 12;
}
minEnd = ('' + minEnd).length > 1 ? minEnd : '0' + minEnd;
$('#etime').append('<option value="' + hourEnd + ':' + minEnd + ' ' + amPm + '">' + hourEnd + ':' + minEnd + ' ' + amPm + '</option>');
time1.setMinutes(time1.getMinutes() + meetingLength);
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<th>Start Time:</th>
<td>
<select name="stime" id="stime">
<option value="0">--Select start time--</option>
</select>
</td>
</tr>
<br/>
<tr>
<th>Metting Length:</th>
<td>
<select name="meet_leng" id="meet_leng">
<option value="0">--Select length--</option>
</select>
</td>
</tr>
<br/>
<tr>
<th>End Time:</th>
<td>
<select name="etime" id="etime" />
<option value="0">--Select end time--</option>
</select>
</td>
</tr>
You want to either set the value:
$('#etime').val("new value");
or select the index:
$('#etime').get(0).selectedIndex = 1;
remember that indexes start at 0.
you would do this after the while loop that populates all the end time options.
Please try below code
$('#meet_leng').on('chnage',function(){
$('#etime').val("FirstIndexValue")
});
//FirstIndexValue= #etime default value

Actual Date in an HTML Table?

<tr>
<td class="tr9 td0"><p class="p1 ft8">Mr. / Mrs. : </p></td>
<td class="tr9 td1"><p class="p3 ft8"><nobr>Telefon: </nobr></p></td>
<td class="tr9 td2"><p class="p4 ft6">DATE</p></td>
</tr>
How can I become the actual Date in Javascript on the Placeholder "DATE" in this table?
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
Doesnt work.
It's because you are writing value directly to HTML. Pass it to element
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
document.getElementsByClassName('p4')[0].innerHtml = "<b>" + day + "/" + month + "/" + year + "</b>";
Or if you are using jQuery:
$('.p4').text("<b>" + day + "/" + month + "/" + year + "</b>");
JSFiddle with pure js and jQuery
The javascript code is working fine but the problem with document.write. it write text on entire document.
so use.
document.getElementsByClassName('p4').innerHTML= "<b>" + day + "/" + month + "/" + year + "</b>";
I tried to debug in firebug and it's seems textcontent property still filled by "DATE", so i set the textContent property become date today, code below maybe can answer your question :
<script>
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
document.getElementsByClassName('p4')[0].textContent = day + "/" + month + "/" + year;
</script>

angular js input date on firefox

I've got these inputs and this model:
<input name="date" type="date" ng-model="model.date" />
<input name="time" type="time" ng-model="model.time" />
model{
date: "yyyy-mm-dd",
time: "hh24:mi"
}
I need the date and the time as a string and that format is ok for what I have to do. The problem is the input date and input time only work properly with Chrome. If I use Firefox these inputs become two simple input text.
What can I do?
As mentioned in W3Schools, the HTML5 input date is not supported in Firefox. Therefore, all input date will become simple input text in Firefox, as well as IE.
So if you only use IE and Firefox, you could use a jQuery datepicker. Use this for your timepicker.
Also, another way but not as nice, is using <select> tags.
Below I used JS (no jQuery) and HTML to create the datepicker and timepicker. Also, I have also created a "Validate" button to validate the values of the date, which means that "31 Feb 2012" and "29 Feb 2014" will be considered invalid.
HTML:
<table><tr><td>Event Date: </td><td> <select id="startday"></select><select id="startmonth">
<option value="01">Jan</option>
<option value="02">Feb</option>
<option value="03">Mar</option>
<option value="04">Apr</option>
<option value="05">May</option>
<option value="06">Jun</option>
<option value="07">Jul</option>
<option value="08">Aug</option>
<option value="09">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select> <select id="startyear"></select></td></tr>
<tr><td>Event Time:</td><td> <select id="starthrs"></select><select id="startmins"></select> [24 hrs clock]</td></tr>
</table><br><br>
<input type="button" id="validate" value="Validate"> <a style="color: Red;" id="error"></a>
JS:
for(var i = 0; i < 24; i++) {
var s = i.toString();
if(s.length == 1) {
s = "0" + s;
}
document.getElementById("starthrs").innerHTML += ("<option value='" + i + "'>" + s + " </option>");
}
for(var i = 0; i < 60; i++) {
var s = i.toString();
if(s.length == 1) {
s = "0" + s;
}
document.getElementById("startmins").innerHTML += ("<option value='" + i + "'>" + s + " </option>");
}
for(var i = 1; i < 32; i++) {
var s = i.toString();
if(s.length == 1) {
s = "0" + s;
}
document.getElementById("startday").innerHTML += ("<option value='" + s + "'>" + i + " </option>");
}
for(var i = new Date().getFullYear(); i < (new Date().getFullYear() + 11); i++) {
document.getElementById("startyear").innerHTML += ("<option value='" + i + "'>" + i + " </option>");
}
function ddlValue(id) {
var e = document.getElementById(id);
var strUser = e.options[e.selectedIndex].value;
return strUser;
}
// Validate date
function isDate(ExpiryDate) { // MM/DD/YYYY format
var objDate, // date object initialized from the ExpiryDate string
mSeconds, // ExpiryDate in milliseconds
day, // day
month, // month
year; // year
// date length should be 10 characters (no more no less)
if (ExpiryDate.length !== 10) {
return false;
}
// third and sixth character should be '/'
if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') {
return false;
}
// extract month, day and year from the ExpiryDate (expected format is mm/dd/yyyy)
// subtraction will cast variables to integer implicitly (needed
// for !== comparing)
month = ExpiryDate.substring(0, 2) - 1; // because months in JS start from 0
day = ExpiryDate.substring(3, 5) - 0;
year = ExpiryDate.substring(6, 10) - 0;
// test year range
if (year < 1000 || year > 3000) {
return false;
}
// convert ExpiryDate to milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// initialize Date() object from calculated milliseconds
objDate = new Date();
objDate.setTime(mSeconds);
// compare input date and parts from Date() object
// if difference exists then date isn't valid
if (objDate.getFullYear() !== year ||
objDate.getMonth() !== month ||
objDate.getDate() !== day) {
return false;
}
// otherwise return true
return true;
}
document.getElementById("validate").onclick = function() {
var startday = parseInt(ddlValue("startday"));
var startmonth = parseInt(ddlValue("startmonth"));
var startyear = parseInt(ddlValue("startyear"));
var starthrs = parseInt(ddlValue("starthrs"));
var startmins = parseInt(ddlValue("startmins"));
// Invalid date
if(!isDate(ddlValue("startmonth") + "/" + ddlValue("startday") + "/" + ddlValue("startyear"))) {
document.getElementById("error").innerHTML = "Invalid date";
return;
}
document.getElementById("error").innerHTML = "";
}
Fiddle. Hope that helped.
AFAIK, 'date' input type is supported only by chrome at the moment. May be this answer will help with your need.

How can I insert a date into a textbox using Javascript?

I'd like to put today's date into a textbox using javascript; Here is my code:
function add_event() {
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var day1 = day + "." + month + "." + year
var html = '<tr><td class="date"><input type="text" name="date_evnt" value="?"></td> <td class="title"><input type="text" value="New Event"></td> <td class="delete"><input type="button" value="-"></td></tr>';
$('#events-table').append(html);
events_table_events();
}
I'm not sure how to set the date into textbox name date_evnt.
If you just want to put the day1 value in date_evnt you can do this:
var html = '<tr><td class="date"><input type="text" name="date_evnt" value="' + day1 + '"></td> <td class="title"><input type="text" value="New Event"></td> <td class="delete"><input type="button" value="-"></td></tr>';
You may try this
function add_event() {
var currentDate = new Date(), day = currentDate.getDate(),
month = currentDate.getMonth() + 1, year = currentDate.getFullYear(),
day1 = day + "." + month + "." + year;
var txt1 = $('<input/>', { 'name':'date_evnt', 'value':day1 }),
tr = $("<tr/>"), td = $('<td/>');
tr.append(td.attr('class','title').html('New Event '))
.append(td.append(txt1))
.append(td.append($('<button/>', {'html':'-'})));
$('#events-table').append(tr);
}
add_event();
DEMO.

Categories