Format a number to time like hh:mm - javascript

I have an iput field:
<input type="text" name="time" class="time" value="3" />
I need that value to be like 03:00
More examples of what I need:
1 = 01:00
12 = 12:00
12:2 = 12:20
2:2 = 02:20
02:2 = 02:20
340 = 340:00
340:1 = 340:10
You know the rest. How can I solve this in jquery/javascript?
This is what I try in jQuery:
$('input').blur(timeFormat);
function timeFormat(e){
skjema.find('input.tid').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
if(tid.length == 1){
$(this).val(String("0" + tid));
}
if(tid.indexOf(':') == -1){
$(this).val(tid.toString() + ':00');
}
}
});
}
This is what I have made now and it does the job, but it is somewhat bulky :)
function timeFormat(e){
skjema.find('input.tid').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
tid = (tid.length == 1) ? '0' + tid : tid;
tid = (tid.indexOf(':') == -1) ? tid + ':00' : tid;
if(tid.indexOf(':') != -1){
var arr = tid.split(':');
var before = arr[0].toString();
var after = arr[1].toString();
before = (before.length == 0) ? '00' : before;
before = (before.length == 1) ? '0' + before : before;
after = (after.length == 0) ? '00' : after;
after = (after.length == 1) ? after + '0' : after;
console.log('before: ' + before + ' After: ' + after);
tid = before + ':' + after;
}
}
$(this).val(tid);
});
}

You can do this with some simple regex:
function time( str ) {
if ( !/:/.test( str ) ) { str += ':00'; }
return str.replace(/^\d{1}:/, '0$&').replace(/:\d{1}$/, '$&0' );
}
If you want to make sure only the expected format is accepted, add this line at the top of the function:
if ( /[^:\d]/.test( str ) ) { return false; }
Demo: http://jsfiddle.net/elclanrs/MzgMz/

YOu can try something like this using datejs library:-
var dateString = "12";
var date = new Date.parseExact(dateString, "hh:mm");

check this DEMO
$('input').blur(timeFormat);
function timeFormat(e){
$("div").find('input').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
if(tid.length == 1){
$(this).val(String("0" + tid));
}
if(tid.indexOf(':') == -1){
$(this).val(tid.toString() + ':00');
}
if(tid.indexOf(':') == 2){
$(this).val(tid.toString() + '0');
}
}
});
}​

<title>Insert Colon in the Time Format</title>
<script type="text/javascript">
function formatTime(objFormField){
intFieldLength = objFormField.value.length;
if(intFieldLength==2 || intFieldLength == 2){
objFormField.value = objFormField.value + ":";
return false;
}
}
</script>
Enter time <input type="text" maxlength="5" minlength="5" onKeyPress="formatTime(this)"/>

Pseudo:
val ← value from field ($('.time').val())
colonPos ← position of . in val
If colonPos equals -1, result ← padZero(val) + ':00'
Else, result ← padZero(val[:colonPos]) + ':' + padZero(val[colonPos + 1:])

function prettyTime(t){
// will output a time providing leading zeros and minute field
// (doesn't need jQuery)
x=t.split(":");
for (var i=0; i<2; i++)
x[i] = (x[i]) ? Array(3-x[i].length).join('0') + x[i] : '00';
return x.join(":");
}
// --
$('input').blur(timeFormat);
function timeFormat(e){
skjema.find('input.tid').each(function(){
$(this).val(function(i, v) { return prettyTime(v); })
});
}

Maybe u can try this plugin.. Worked for me
Usage Examples:
$("#tbPlain").timefield();
$("#tb12Hour").timefield({ 'hourFormat': '12'});
$("#tb24Hour").timefield({ 'hourFormat': '24'});
$("#tbWithInvalidHandler").timefield({
'hourFormat': '24',
'onError' : function(){
alert(this.value+' is not a valid time!');
this.style.backgroundColor='red';
}
});
$("#tbOnOff").timefield();
$("#btnTurnOff").click(function(){
$("#tbOnOff").timefield('turnOffTimeField');
});
Live Example:
https://jsfiddle.net/sajjansarkar/bst3cw2g/

Related

Phone Number Validation With Spacing

I have researched all over the place for a phone number validation in JavaScript that adds spacing as they type.
The closest code I came to was
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
while (val.length > 3) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
newVal += val;
this.value = newVal;
});
http://jsfiddle.net/ssthil/nY2QT/.
Expect that is American Mobile Numbers. Anyone know how to do Australia format (XXXX XXX XXX). I tried moving the digits around in the JavaScript but nothing seemed to work.
Try this code :
while (val.length > 3) {
if(newVal.length > 4){
newVal += val.substr(0, 3) + ' ';
val = val.substr(3);
} else {
newVal += val.substr(0, 4) + ' ';
val = val.substr(4);
}
}
newVal += val;
this.value = newVal;
});
Working fiddle :
http://jsfiddle.net/nY2QT/718/
Modifying your code a little bit you can get something like this:
$('#ssn').on('input', function() {
var val = this.value.replace(/\D/g, '');
if(val.length > 10) {
this.value = this.value.slice(0,12);
} else {
this.value = (val.slice(0,4) + ' ' + val.slice(4,7) + ' ' + val.slice(7,10)).trim();
}
});
I have made some changes with loop hope it will works
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
var flag = true;
while (val.length > 3) {
if(flag){
flag=false;
newVal += val.substr(0, 4) + '-';
val = val.substr(4);
} else {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
}
newVal += val;
if(this.value.length >= 5){
this.value = newVal;
}
});
You could have instead three <input /> elements, give them each maxlength="4", maxlength="3", and maxlength="3" respectively. And as soon as the user completes each input, they're moved to the following:
HTML
<form>
<input maxlength="4" autofocus="autofocus" name="first"/>
-
<input maxlength="3" name="second"/>
-
<input maxlength="3" name="third"/>
</form>
Javascript/jQuery
// Autofocus second after first is complete
$('[name="first"]').keyup(function() {
if ( $(this).val().length == 4) {
$('[name="second"]').focus();
}
});
// Autofocus third after second is complete
$('[name="second"]').keyup(function() {
if ( $(this).val().length == 3) {
$('[name="third"]').focus();
}
});
// Alert numer after third is complete
$('[name="third"]').keyup(function() {
if ( $(this).val().length == 3) {
alert("Number: " + $('[name="first"]').val() + "-" + $('[name="second"]').val() + "-" + $('[name="third"]').val() + ".");
}
});
Also, to valide for only numbers, you can use RegEx:
// The following code is RegEx, used to validate the inputs so that the user can only type in numbers
$('[name="first"], [name="second"], [name="third"]').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
// Support for old browsers
$('[name="first"], [name="second"], [name="third"]').on('keyup', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
Eureka!
Edit: answer to Z-Dog's "question":
// Autofocus first if backspace is pressed and this is empty
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '8' && $(this).val().length == 0){
$('[name="first"]').focus();
// And delete last character
$('[name="first"]').val(
function(index, value){
return value.substr(0, value.length - 1);
});
return false;
}
Eureka 2.0!
Use Jquery Mask plug-in
https://igorescobar.github.io/jQuery-Mask-Plugin/
It simple to integrate ans use
Use this code it might work
document.getElementById('ssn').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/(\d{4}) ?(\d{3}) ?(\d{3})/,
'$1 $2 $3');
});

How to insert delimitter on key up after 7 letters/alphabet/numbers and new letters in new line- Jquery

How to put comma after 7 letters on keyup event,Below is my code where I am able to get comma after 7 letters but when it goes to next line it doesn't work properly.
<asp:TextBox ID ="txtbillno" runat="server" onkeyup="InsertComma();" TextMode="MultiLine"></asp:TextBox>
function InsertComma() {
var txtObj = document.getElementById('<%=txtbillno.ClientID %>');
var txtVal = replaceAll(txtObj.value, ',', '');
if (txtObj.value != "") {
var newVal = "";
for (var i = 0; i < txtVal.length; i++) {
newVal = newVal + txtVal.substring(i, i + 1);
if ((i + 1) % 7 == 0 && i != 0) {
newVal = newVal + "," + "\n";
}
}
txtObj.value = newVal;
}
}
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'), with_this);
}
In your InsertComma function you were correctly removing the commas:
var txtVal = replaceAll(txtObj.value, ',', '');
but txtVal still contains the new line characters (\n), so I added a line to remove those too:
txtVal = replaceAll(txtVal, '\n', '');
The complete InsertComma method is:
function InsertComma() {
var txtObj = document.getElementById('txtbillno');
// Remove commas
var txtVal = replaceAll(txtObj.value, ',', '');
// Remove new line characters
txtVal = replaceAll(txtVal, '\n', '');
if (txtObj.value != "") {
var newVal = "";
// Append commas
for (var i = 0; i < txtVal.length; i++) {
newVal = newVal + txtVal.substring(i, i + 1);
if ((i + 1) % 7 == 0 && i != 0) {
newVal = newVal + "," + "\n";
}
}
txtObj.value = newVal;
}
}
and a working example can be found here

How to do date masking using javascript (without JQuery)?

<![CDATA[
var $ = jQuery;
String locale = getUserLocale();
$(document).ready(function() {
if (!isEmptyNull(locale) && locale.equals("zh_CN")) {
$("input[id*='text12']").mask('9999年99月99日');
}
else {
$("input[id*='text12']").mask('99/99/9999');
}
});
]]>
<p:calendar id="text12" styleClass="calendar" maxlength="10" pattern="#
{pc_Test.dateDisplayFormat}"></p:calendar>
If the locale is equal to 'zh_CN', the masking would be '9999年99月99日'. Otherwise, it would would be '99/99/9999'.
When I remove the if else command, it works. But if I put the if else command inside, it doesn't work.
How do I solve it?
Check out the below code..
<input
type="text"
name="date"
placeholder="dd/mm/yyyy"
onkeyup="
var v = this.value;
if (v.match(/^\d{2}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
<input
type="text"
name="date"
placeholder="mm/dd/yyyy"
onkeyup="
var v = this.value;
if (v.match(/^\d{2}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
<input
type="text"
name="date"
placeholder="yyyy/mm/dd"
onkeyup="
var v = this.value;
if (v.match(/^\d{4}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{4}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
<input
type="text"
name="date"
placeholder="yyyy年mm月dd"
onkeyup="
var v = this.value;
if (v.match(/^\d{4}$/) !== null) {
this.value = v + '年';
} else if (v.match(/^\d{4}年\d{2}$/) !== null) {
this.value = v + '月';
}"
maxlength="10"
>
Hope this is what you are looking for!
I had some trouble getting the currently accepted answers to work properly while retaining the ability to backspace. This was my solution. It retains backspacing and also doesn't show the slash until the number following it is typed.
const maskDate = value => {
let v = value.replace(/\D/g,'').slice(0, 10);
if (v.length >= 5) {
return `${v.slice(0,2)}/${v.slice(2,4)}/${v.slice(4)}`;
}
else if (v.length >= 3) {
return `${v.slice(0,2)}/${v.slice(2)}`;
}
return v
}
I've also create a github gist for this snippet here.
I have solved this issue a simple function(without regular expressions and only for the format 'dd/mm/yyyy'). And the important thing is that My function pays attention to the maximum values of the date(31) and month(12). For example, You can not input 32/11/2000 or 20/13/2000.
function maskForDate(value) {
if (value.length > 10) {
return value.substring(0, 10);
}
switch (value.length) {
case 1:
if (value > 3) {
value = "3";
}
break;
case 2:
if (value > 31) {
value = "31";
}
break;
case 3:
case 4:
if (value[2] !== "/") {
value = value.substr(0, 2) + "/" + value[2];
}
if (value[3] > 1) {
value = value.substr(0, 3) + "1";
}
break;
case 5:
if (value.substr(3, 2) > 12) {
value = value.substr(0, 3) + "12";
}
break;
case 6:
case 7:
if (value[5] !== "/") {
value = value.substr(0, 5) + "/" + value[5];
}
if (value[6] < 1) {
value = value.substr(0, 6) + "1";
}
break;
default:
break;
}
return value;
}
Try out this code, this will format your date in mm/dd/yyyy format as you type it in the input box.
Create an onchange event on the input box and call the date_formator function with the input date.
function date_formator(date) {
date = date.replace('//', '/');
var result = date.split("/");
var length = result.length;
// Append "/" after the last two charas, if more than 2 charas then remove it
if (length <= 2 && result[length - 1] != "") {
var last_two_digits = result[length -1];
if (last_two_digits.length >= 2) {
date = date.slice(0, -last_two_digits.length);
date = date + last_two_digits.slice(0,2) + "/";
}
}
if (typeof result[2] != "undefined") {
var year = result[2];
if (year.length > 4) {
date = date.slice(0, -year.length);
year = year.slice(0, 4);
date = date + year;
}
}
return date;
}
This works quite well (tried it in console on the jquery mask page)
if (locale !=='' && locale==='zh_CN') {
$('#text12').mask('9999年99月99日');
}
else {
$('#text12').mask('99/99/9999');
}
but if you want the mask format to show up in the input field you need to pass it as placeholder attribute
$('#text12').attr('placeholder', '9999年99月99日')
hope this helps

Pop up once every 30 days

I am totally novice for JS and cookies. I got this code online and tried to change it for 30 days (it was set to 365) but it's probably resetting the cookie for every page and the pop up appears if I go to other page or even return back to the original page. Only things I changed in the code was expire days to 30 and load delay of 30 secs.
It seems either it's resetting the cookie every time I move to other page or some other problem which I don't understand yet :). I was wondering if there is some more efficient way to have it rather putting the code in every html article page. Something like setting up a cookie in headers or something and recalling using body onload.
Here is the code:
<SCRIPT language=JavaScript>
<!--
var expDays = 30; // number of days the cookie should last
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value,expires) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function checkCount() {
var count = GetCookie('poponce');
if (count == null) {
count++;
SetCookie('poponce', count, exp);
// Action to take
dothis()
}
}
setTimeout(function dothis(){
var windowprops = "left=300,top=240,width=600,height=400,location=no,toolbar=no,menubar=no,scrollbars=no";
window.open("/subscribepopup.html", "", windowprops); // Use to load a page
}, 30000);
// -->
</SCRIPT>
<body OnLoad="checkCount()">

JavaScript Validation on Time Field (0:00 format not accepted)

Here is my code for validating incorrect time formats:
$('.allts').delegate(".tf", "focusout", function (e)
{
var curval = this.value;
curval = curval.replace(';', ':');
curval = curval.replace(" ", ':');
curval = curval.replace('.', ':');
//alert(curval);
if (/^\d$/.test(curval))
{
curval = "0" + curval + ":00";
}
if (/^[0-9]:[0-5][0-9]$/.test(curval))
{
curval = "0" + curval;
}
if (curval >= 10 && curval <= 12)
{
curval = curval + ":00";
}
if(curval.length==2&&curval >= 0 && curval <= 12){
curval = curval + ":00";
}
this.value = curval;
if (this.value != "")
{
if (!isValidDate(curval))
{
this.style.background = "#faa";
$('#msg_tformat').html('Please enter a valid time').show();
this.value = "";
}
My requirement is not to accept the 0:00 time format. If I give time formats like 0:00 it should display an error message like: "Please enter a valid time". Can anyone suggest the
proper way to validate for this in JavaScript?
Thanks in advance.
add to the isValidDate function something like this:
if( curval === '0:00' || curval === '00:00' ) {
return false;
}

Categories

Resources