Insert Date and time in textbox when button is clicked - javascript

I am creating something that would generally enter the date and time in the textbox. How can I format the date and time that will only display MM/DD/YYYY ##:##:## inside the textbox. I would like it simple and can be run to IE of any version.
Here is my code:
<form>
<input name="StartDate" size="50">
<input onclick="this.form.StartDate.value = new Date();" type="button" value="Start date">
<input name="StopDate" size="50">
<input onclick="this.form.StopDate.value = new Date();" type="button" value="Stop date">
</form>

You can use getMonth, getYear methods etc. on a date object - this should be supported in older versions of IE.
var myDate = new Date();
this.form.StopDate.value = (myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myDate.getFullYear()+ ' ' + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();
See Docs
It may makes sense to define this as a function:
function getDateString(){
var myDate = new Date();
return (myDate.getMonth() + 1) +
"/" + myDate.getDate() +
"/" + myDate.getFullYear() +
' ' + myDate.getHours() +
":" + myDate.getMinutes() +
":" + myDate.getSeconds();
}
And then use in your button:
<input onclick="this.form.StartDate.value = getDateString();" type="button" value="Start date">
You may also need to handle adding leading 0's to your date, this snippet takes care of this:
function getDateString(){
var myDate = new Date();
return padDatePart(myDate.getMonth() + 1) +
"/" + padDatePart(myDate.getDate()) +
"/" + myDate.getFullYear()+
' ' + padDatePart(myDate.getHours()) +
":" + padDatePart(myDate.getMinutes()) +
":" + padDatePart(myDate.getSeconds());
}
function padDatePart(part){
return ('0'+part).slice(-2);
}
<form>
<input name="StartDate" size="50">
<input onclick="this.form.StartDate.value = getDateString();" type="button" value="Start date">
<input name="StopDate" size="50">
<input onclick="this.form.StopDate.value =getDateString();" type="button" value="Stop date">
</form>

Related

Convert input into string/var and use it in an alert

I am using an input and want to covert it into a string/var to print it out in an alert after i click on a button.
I need the input of "Forename:" to add into the button "send" with "onlcick".
The alert is just a debuger. Instead of alert i want to use a function. Using onclick="printPDF(foreName+' '' ' + da + '.' + mo + '.' + ye + '_' + h + ':' + m + ':' + s + '.pdf');
function startTime() {
var today = new Date();
var da = today.getDate();
var mo = today.getMonth() + 1;
var ye = today.getFullYear();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
<p>
<label>Forename:</label>
<input class="w3-input w3-white" id="some1" type="text" name="some1" value="asd" maxLength="200">
</p>
<button id="snbtn1" type="submit" class="w3-btn w3-green" onclick="alert(' ' + da + '.' + mo + '.' + ye + '_' + h + ':' + m + ':' + s + '.pdf');">send</button>
<script>
function startTime() {
var today = new Date();
var da = today.getDate();
var mo = today.getMonth()+1;
var ye = today.getFullYear();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
var foreName = document.getElementById('some1').value;
alert(foreName+' ' + da + '.' + mo + '.' + ye + '_' + h + ':' + m + ':' + s + '.pdf');
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
<p>
<label>Forename:</label>
<input class="w3-input w3-white" id="some1" type="text" name="some1" value="asd" maxLength="200">
</p>
<button id="snbtn1" type="submit" class="w3-btn w3-green" onclick="startTime();">send</button>
You should put your onclick code into a function in your javascript code, by getting the button element and adding an event listener to it. In the same way you get the button in your javascript code you can get the input and it's value:
var today = new Date();
var da = today.getDate();
var mo = today.getMonth()+1;
var ye = today.getFullYear();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//m = checkTime(m);
//s = checkTime(s);
document.getElementById("snbtn1").addEventListener("click", function() { // Get the button and add an onclick event listener to it
alert(' ' + da + '.' + mo + '.' + ye + '_' + h + ':' + m + ':' + s + '.pdf');
alert(document.getElementById("some1").value); // Get the input by it's id and alert the value
});
<p>
<label>Forename:</label>
<input class="w3-input w3-white" id="some1" type="text" name="some1" value="asd" maxLength="200">
</p>
<button id="snbtn1" type="submit" class="w3-btn w3-green">send</button>
https://developer.mozilla.org/he/docs/Web/API/Document/getElementById
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

How to get new time or date on every button click in Jquery?

When I enter multiple notes on button click Jquery date and time auto fill up in the textbox. Like this,
But when I click After two-minute date and time not change its display same as first selected.
Below the Code :
Jquery Date and Time Code:
var nowDate = new Date();
var mm = nowDate.getMonth() + 1; mm = (mm < 10) ? '0' + mm : mm;
var dd = nowDate.getDate(); dd = (dd < 10) ? '0' + dd : dd;
var new_today = mm + '/' + dd + '/' + nowDate.getFullYear();
var mi = nowDate.getMinutes(); mi = (mi < 10) ? '0' + mi : mi;
var time = nowDate.getHours() + ":" + mi;
Dynamic HTML Code
function addCallImage() {
html = '<tr id="call-row' + call_row + '" style="background-color: cadetblue;">';
html += ' <td class="text-left col-md-6"><textarea rows="4" cols="50" name="case_intake_call_record[' + call_row + '][caller_name]" placeholder="Enter Call Record" class="form-control" value="" id="input-call' + call_row + '" ></textarea></td>';
html += ' <td class="text-right col-md-3"><div class="input-group" data-date-format="mm/dd/yyyy" data-date-end-date="0d"><input type="text" name="case_intake_call_record[' + call_row + '][caller_date]" placeholder="MM/DD/YYYY" class="form-control" value="'+new_today+'"> <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></div></td>';
html += ' <td class="text-right col-md-3"><div class="input-icon"><i class="fa fa-clock-o"></i><input type="text" class="form-control" name="case_intake_call_record[' + call_row + '][caller_time]" value="'+time+'"></div></td>';
html += '</tr>';
$('#calls tbody').append(html);
call_row++;
clicks += 1;
document.getElementById("autoCall").innerHTML = clicks;
$("#autoCallhidden").val(clicks);
}
View File Code
<tr>
<td class="text-left" colspan="4"><button type="button" onclick="addCallImage();" data-toggle="tooltip" title="" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button>Click to Add Call Record</td>
</tr>
Each time the button click action occurs, you will want to make the function calls to nowDate. Try declaring the vars locally within the addCallImage() function so that they are reset every time the click occurs.
Use new Date inside your function.So when function called then new Date and time generated.
This answer from Mobile so answer maybe not in welll format. :)
var nowDate = new Date(); var mm = nowDate.getMonth() + 1; mm = (mm <
10) ? '0' + mm : mm; var dd = nowDate.getDate(); dd = (dd < 10) ? '0'
+ dd : dd; var new_today = mm + '/' + dd + '/' + nowDate.getFullYear(); var mi = nowDate.getMinutes(); mi = (mi < 10) ?
'0' + mi : mi; var time = nowDate.getHours() + ":" + mi;
<script>
$(document).ready(function(){
$('li').on('click',function(e){
$('li span').remove();
var date = new Date();
var date = date.toDateString();
console.log(date);
$(this).append( ' <span> ' + date + '</span>');
});
});
</script>
<body>
<div>
<h1>List</h1>
<h2>Buy Fruits</h2>
<ul>
<li id="one"><em>fresh</em> Apple</li>
<li id="two">Lemon</li>
<li id="three">Orange</li>
<li id="four">Grapes</li>
</ul>
</div>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous"></script>
</body>
Similarly you can use date.toTimeString() to get the time from Unix Timestamp.
To view this code in codepen visit:
https://codepen.io/saurav0083/pen/ZEbewVj

JavaScript and JQuery: Displaying Time in Text box

I want to display time only in the text field in HTML using JavaScript but its not showing. Kindly help me out.
<input type="text" name="time1" id="e1" value="" />
<script>
function display_ct() {
var strcount
var x = new Date()
var x1=x.getMonth() + "/" + x.getDate() + "/" + x.getYear();
x1 = x1 + " - " + x.getHours( )+ ":" + x.getMinutes() + ":" + x.getSeconds();
//document.getElementById('ct').innerHTML = x1;
//tt=display_c();
document.getElementById('e1').value = x1;
}
</script>
All you need to do is call your function.
HTML
<input type="text" name="time1" id="e1" value="" />
JavaScript
function display_ct() {
var strcount
var x = new Date()
var x1=x.getMonth() + "/" + x.getDate() + "/" + x.getYear();
x1 = x1 + " - " + x.getHours( )+ ":" + x.getMinutes() + ":" + x.getSeconds();
//document.getElementById('ct').innerHTML = x1;
//tt=display_c();
document.getElementById('e1').value = x1;
}
display_ct();
JSFiddle
http://jsfiddle.net/aGGHQ/
getYear is no longer used and has been replaced by the getFullYear method.
var x1=x.getMonth() + "/" + x.getDate() + "/" + x.getFullYear();

Opening a dynamically built Google URL in new window

I'm using modified code originally supplied by Google to make a transit trip planner form that uses Google Maps. I'd like the results to open in a new window/tab so the user doesn't have to leave the site (I realize this is a somewhat controversial usability issue, but this is at my client's behest, so...).
The code below uses target="_blank" in the tag - which seemed like the simplest solution - but that doesn't work in this instance - not sure why, but thought it may have something to do with the dynamically-built URL.
I tried several methods gleaned from previous similar questions on this site, the method below being one of them, as well as something along the lines of
myForm.setAttribute("target", "_blank");
but so far nothing has been successful.
Here's the code I'm using. Any suggestions would be greatly appreciated.
<script language="JavaScript" type="text/javascript">
// Edit the strings below this line
var startExample = "USC";
var endExample = "201 N Los Angeles St.";
var zip = "90012";
// End edit block
// Get and parse the user's current date/time
var date = new Date();
var isPM = false;
var currentTime = date.getHours();
var currentDate = "";
var amOption = '<option value="am">AM';
var pmOption = '<option value="pm">PM';
if(currentTime > 11)
isPM = true;
currentTime %= 12;
if(currentTime == 0)
currentTime = 12;
currentTime += ':';
if(date.getMinutes() < 10)
currentTime += '0';
currentTime += date.getMinutes();
if(isPM)
pmOption = '<option selected="true" value="pm">PM';
else
amOption = '<option selected="true" value="am">AM';
if(date.getMonth() < 9)
currentDate = '0';
currentDate += (date.getMonth() + 1) + '/';
if(date.getDate() < 10)
currentDate += '0';
currentDate += date.getDate() + '/' + date.getFullYear();
// Builds the destination URL
function buildURL() {
var loc = 'http://www.google.com/maps?ie=UTF8&f=d&';
for (var i = 0; (i < document.myForm.length - 1); i++) {
if(document.myForm[i].name == 'ampm')
continue;
if(document.myForm[i].name == 'time')
loc += document.myForm[i].name + '=' + document.myForm[i].value + document.myForm.ampm.value + '&';
else {
if(document.myForm[i].name == 'saddr')
loc += document.myForm[i].name + '=' + document.myForm[i].value + '+near+' + zip + '&';
else
loc += document.myForm[i].name + '=' + document.myForm[i].value + '&';
}
}
loc+='dirflg=r';
location.href=loc;
return true;
}
</script>
<form name="myForm" id="myForm" action="#" target="_blank">
<p>Powered by Google Maps</p>
<label for="saddr"><strong>Start</strong> e.g.
<script language="JavaScript" type="text/javascript">
document.write(startExample)
</script>
</label>
<input type="text" name="saddr" maxlength="2048" title="Enter the Origin Address" class="startend" />
<label for="daddr"><strong>End</strong> e.g.
<script language="JavaScript" type="text/javascript">document.write(endExample)</script></label>
<input type="text" name="daddr" maxlength="2048" title="Enter the Destination Address" class="startend" />
<div class="gadgetform-row">
<script language="JavaScript" type="text/javascript">
document.write('<div class="datewrapper">');
document.write('<label for="date"><strong>Date</strong></label><br />');
document.write('<input class="date" type="text" id="fdate" name="date" value="' + currentDate + '" maxlength="10" title="Enter the Date in MM/DD/YY format">');
document.write('</div>');
document.write('<div class="timewrapper">');
document.write('<label for="time"><strong>Time</strong></label><br />');
document.write('<input class="time" type="text" id="ftime" name="time" value="' + currentTime + '" maxlength="8" title="Enter the Time in HH:MM AM or PM format">');
document.write('</div>');
document.write('<div class="ampmwrapper">');
document.write(' <br />');
document.write('<select name="ampm" class="ampm">' + amOption + pmOption + '</select>');
document.write('</div>');
document.write('<div class="clear"></div>');
</script>
</div>
<div class="planby">
<label for="ttype"><strong>Plan by:</strong> </label
><select name="ttype">
<option value="dep">Departure Time </option>
<option value="arr">Arrival Time</option>
</select>
</div>
<a class="button" href="javascript:void();" onclick='return buildURL();'><span class="plan">Plan My Trip</span></a>
</form>
You can try using window.open instead. Here's a function that I created for opening child windows:
openChildWindowWithDimensions = function(url, width, height, showMenu, canResize, showScrollbars) {
var childWindow = window.open(url, "", "\"width=" + width + ",height=" + height + ",menubar=" + (showMenu ? "1" : "0") + ",scrollbars=" + (showScrollbars ? "1" : "0") + ",resizable=" + (canResize ? "1" : "0") + "\"");
if (childWindow){
childWindow.resizeTo(width, height); //IE9 dimensions bug
}
}
Add this function to your page, and at the end of your function that builds the URL, call it like this:
openChildWindowWithDimensions(loc, 800, 600, true, true, true);

Javascript to generate a time string in an online form

I have a html form like this :
<form action="https://www.123.com/cgi-bin/action" method="post">
<input type="hidden" name="item_name" value="Product Name">
<input type="hidden" name="item_number" value="Product Name_2010_12_21_15_03">
<input type="hidden" name="amount" value="29.99">
</form>
How to use javascript to replace the above "Product Name_2010_12_21_15_03" with dynamically generated time string ?
<script type="text/javascript">
<!--
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write("Product Name+" + year + "_" + month + "_" + day)
//-->
</script>
You can just set the value of the input:
<input id='product_date_time' type='hidden' name='item_number' value=''>
<script>
document.getElementById('product_date_time').value = new Date().toString();
</script>
The script does not have to immediately follow the input field, of course. It simply has to run at some point after the input element has been added to the DOM.
If you need more control over the format, you might want to look into the venerable Date.js library.
Based on your comment for the format "2010_12_21_15_03":
<input id='product_date_time' type='hidden' name='item_number' value=''>
<script>
function myDate () {
var d = new Date();
return d.getFullYear() + "_" + (d.getMonth() + 1) + "_" + d.getDate() + "_" + d.getHours() + "_" + d.getMinutes();
}
document.getElementById('product_date_time').value = myDate();
</script>
Ok, I got it :
<form action="https://www.123.com/cgi-bin/action" method="post" name="My_Form">
<input type="hidden" name="item_name" value="Product_Name">
<input type="hidden" name="item_number" value="Product_Name">
<input type="hidden" name="amount" value="9.99">
<script type="text/javascript">
<!--
function getCorrectedYear(year)
{
year=year-0;
if (year<70) return (2000+year);
if (year<1900) return (1900+year);
return year;
}
var today=new Date();
var minute=today.getMinutes();
if(minute<10) minute='0'+minute;
var hour=today.getHours();
if(hour<10) hour='0'+hour;
var day=today.getDate();
if(day<10) day='0'+day;
var month=today.getMonth()+1;
if(month<10) month='0'+month;
var year=getCorrectedYear(today.getYear());
var dateString=year+'_'+month+'_'+day+'_'+hour+'_'+minute;
document.My_Form.item_number.value=document.My_Form.item_name.value+'_'+dateString;
//-->
</script>
</form>

Categories