jquery- How to automatically insert colon after entering 2 numeric digits - javascript

I want a to have a text box which accepts HH:MM(hours/minutes) format. So, when the user enters the value for HH, it should automatically insert a colon after that and let the user enter value for MM.
I do not want to use any plugin for this.
How do i do this?
thanks

HTML:
<input class="time" type="text"/><br/>
<input class="time" type="text"/><br/>
<input class="time" type="text"/>
JS:
var time = document.getElementsByClassName('time'); //Get all elements with class "time"
for (var i = 0; i < time.length; i++) { //Loop trough elements
time[i].addEventListener('keyup', function (e) {; //Add event listener to every element
var reg = /[0-9]/;
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
});
};
Fiddle

If you have multiple inputs
<input class="test-input" placeholder="hh:mm" value=""/>
<input class="test-input" placeholder="hh:mm" value=""/>
<input class="test-input" placeholder="hh:mm" value=""/>
<input class="test-input" placeholder="hh:mm" value=""/>
<input class="test-input" placeholder="hh:mm" value=""/>
Jquery Version:
$(document).on('ready',function(){
$('.test-input').on('keyup',keyUpHandler);
});
function keyUpHandler(e){
var element = this;
var key = e.keyCode || e.which;
insertTimingColor(element,key)
}
function insertTimingColor(element,key){
var inputValue = element.value;
if(element.value.trim().length == 2 && key !== 8){
element.value = element.value + ':';
}
}
fiddle - jquery
Vanilla JS version
document.body.addEventListener('keyup',keyUpHandler,false);
function keyUpHandler(e){
var evt = e || window.event;
var target = evt.target || evt.srcElement;
var key = e.keyCode || e.which;
//check if it is our required input with class test input
if(target.className.indexOf('test-input') > -1){
insertTimingColor(target,key)
}
}
function insertTimingColor(element,key){
var inputValue = element.value;
if(element.value.trim().length == 2 && key !== 8){
element.value = element.value + ':';
}
}
fiddle - js

$('id or class or parent id').on('keypress','class or id', function (e){
var key = e.keyCode || e.which;
if(this.value.trim().length == 2 && key !==8 && this.value.search
(':') != -1)
this.value = this.value + ':';
});
$('id or class or parent id').on('keyup click','class or id', function (e){
if(this.value.length >= 3)
this.selectionStart = this.selectionEnd = this.value.length;
});
$('id or class or parent id').on('paste','class or id', function (e){
e.preventDefault();
});

Try it.
jQuery("#textboxId").keypress(function(){
if(jQuery("#textboxId").val().length)==2{
var value=jQuery("#textboxId").val();
jQuery("#textboxId").val(value+":");
}
});

Try the following code:
HTML:
<input type="text" id = "timeInput" maxlength = 14>
Javascript:
$("#timeInput").focusin(function (evt) {
$(this).keypress(function () {
content=$(this).val();
content1 = content.replace(/\:/g, '');
length=content1.length;
if(((length % 2) == 0) && length < 10 && length > 1){
$('#timeInput').val($('#timeInput').val() + ':');
}
});
});
DEMO

$(document).ready(function() {
var global_flag = true;
$("#texboxId").on('keyup', function() {
var cur_val = $(this).val();
var cur_length = cur_val.length;
var flag = true;
if (cur_length > 5) {
cur_val = cur_val.substring(0, 5);
$(this).val(cur_val);
} else {
if (cur_length > 2) {
global_flag = false;
} else if (global_flag == false && cur_length < 2) {
global_flag = true;
}
if (cur_length == 2 && global_flag) {
if (window.event.keyCode != 8) {
$(this).val(cur_val + ":");
}
}
if (cur_length == 5) {
if (cur_val.match(/^(([0-1][0-9]){0,2}|(2[0-3]){0,2}){0,2}:([0-5][0-9]){0,2}$/)) {} else {
$(this).val("");
$(this).attr('placeholder', "HH:MM");
}
}
}
});
});

The code below should do the trick for you. Now all you will need to do is add some validation, like only allowing numeric key press values.
<input id="time-input" placeholder="hh:mm" type="text">
$(document).ready(function(){
$("#time-input").keypress(function(){
$this = $(this);
if($this.val().length == 2){
$this.val($this.val() + ":");
}
});
});
http://jsfiddle.net/g9nahpax/

Related

replace without using a dot how to do?

I have the following code, but I want to replace it without a dot
nominal without separator
function convertToRupiah(angka){
var rupiah = '';
var angkarev = angka.toString().split('').reverse().join('');
for(var i = 0; i < angkarev.length; i++)
if(i%3 == 0) rupiah += angkarev.substr(i,3)+'.';
return rupiah.split('',rupiah.length-1).reverse().join('');
}
function showkerugian(str) {
var temuan = str.replace(/\./g, "",); // update pattern to regex in order to replace all `.` occurrences
$('#nilai_potensi_kerugian').val(convertToRupiah(temuan));
};
$('input#nilai_temuan') .on('keyup focusin focusout ', function(event) {
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" oninput="showkerugian(this.value)" class="form-control nominal" id="nilai_temuan" name="nilai_temuan" >
<input type="text" class="form-control nominal" name="nilai_potensi_kerugian" id="nilai_potensi_kerugian" readonly>
can you solve the problem, help me
Assuming you want the input to contain dots and the output to not have any:
function convertToRupiah(angka){
var rupiah = '';
var angkarev = angka.toString().split('').reverse().join('');
for(var i = 0; i < angkarev.length; i++)
if(i%3 == 0) rupiah += angkarev.substr(i,3);
return rupiah.split('',rupiah.length).reverse().join('');
}
function showkerugian(str) {
var temuan = str.replace(/\./g, "",); // update pattern to regex in order to replace all `.` occurrences
$('#nilai_potensi_kerugian').val(convertToRupiah(temuan));
};
$('input#nilai_temuan') .on('keyup focusin focusout ', function(event) {
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" oninput="showkerugian(this.value)" class="form-control nominal" id="nilai_temuan" name="nilai_temuan" >
<input type="text" class="form-control nominal" name="nilai_potensi_kerugian" id="nilai_potensi_kerugian" readonly>
The issue was that on this line
if(i%3 == 0) rupiah += angkarev.substr(i,3)+'.'; you added a "."

html Input type number with Thousand Separator

i want to add thousand separator on keyup event in input type number
but this work just in 6 character, if more than 6 character, value on input has reseted
this my short code
<input type="number" id="tanpa-rupiah" step="any">
var dengan_rupiah = document.getElementById('dengan-rupiah');
dengan_rupiah.addEventListener('keyup', function(e)
{
dengan_rupiah.value = formatRupiah(this.value, 'Rp. ');
});
function formatRupiah(bilangan, prefix)
{
var number_string = bilangan.replace(/[^,\d]/g, '').toString(),
split = number_string.split(','),
sisa = split[0].length % 3,
rupiah = split[0].substr(0, sisa),
ribuan = split[0].substr(sisa).match(/\d{1,3}/gi);
if (ribuan) {
separator = sisa ? '.' : '';
rupiah += separator + ribuan.join('.');
}
rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
}
this my fiddle https://jsfiddle.net/C2heg/4619/
This might suit you. On keydown prevent the default action if it is not a number key. On keyup, parse the value and update it. Use the data- attributes to store and get the original value.
var elem = document.getElementById("num");
elem.addEventListener("keydown",function(event){
var key = event.which;
if((key<48 || key>57) && key != 8) event.preventDefault();
});
elem.addEventListener("keyup",function(event){
var value = this.value.replace(/,/g,"");
this.dataset.currentValue=parseInt(value);
var caret = value.length-1;
while((caret-3)>-1)
{
caret -= 3;
value = value.split('');
value.splice(caret+1,0,",");
value = value.join('');
}
this.value = value;
});
function showValue()
{
console.log(document.getElementById("num").dataset.currentValue);
}
<input type="text" id="num" maxlength="30">
<button onclick="showValue()">Get Value</button>
Ok I have posted answer below. I have added limit of 20 numbers. You can change it as per your need.
You can use Number.toLocaleString() for this purpose.
Below is working example:
// When ready.
$(function() {
var extra = 0;
var $input = $("#amount");
$input.on("keyup", function(event) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if (selection !== '') {
return;
}
// When the arrow keys are pressed, abort.
if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
if (event.keyCode == 38) {
extra = 1000;
} else if (event.keyCode == 40) {
extra = -1000;
} else {
return;
}
}
var $this = $(this);
// Get the value.
var input = $this.val();
var input = input.replace(/[\D\s\._\-]+/g, "");
input = input ? parseInt(input, 10) : 0;
input += extra;
extra = 0;
$this.val(function() {
return (input === 0) ? "" : input.toLocaleString("en-US");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="amount" name="amount" type="text" maxlength="20" />
change your the input type equal to "text" then its work
<input type="text" id="tanpa-rupiah" step="any">
checkout jsfiddle

JavaScript: Function does not format the numbers properly

I have a function that puts commas every 4 numbers so that it is formatted for currency. The problem is that the first 4 numbers does not add a comma where it should, it only formats everything correctly when a space is entered. Also, why does my input allow the spacebar to be entered when I set it not to? Thanks!
<script>
//Gets the value of the key that was pressed
function keypress(e){
var z="";
var minStr = document.getElementById('min').value;
var charval = String.fromCharCode(e.keyCode);
var backspaceKey = String.fromCharCode(8);
var tabKey = String.fromCharCode(9);
var enterKey = String.fromCharCode(13);
var spaceBarKey = String.fromCharCode(32);
//Validates that only numbers and specific types of keys can be entered
if( isNaN(charval) &&
charval != backspaceKey &&
charval != tabKey &&
charval != enterKey &&
charval == spaceBarKey){
return false;
}
//Start of the function that adds commas
if(minStr.length > 1
&& charval != backspaceKey
&& charval != tabKey
&& charval != enterKey
){
//adds commas to the string
minStr = minStr.replace(/\D/g, "");
var minArray = minStr.split("");
var j = 0;
for(var i = minStr.length; i > 0; i--){
if(j == 3){
minArray.splice(i, 0, ",");
j = 0;
}
j++;
}
minArray = minArray.join("");
document.getElementById('min').value = minArray;
//Here is where it adds a comma to the first 4 numbers
if(minStr.length == 4){
var minArray = minStr.split("");
minArray.splice(1, 0, ",");
minArray = minArray.join("");
document.getElementById('min').value = minArray;
}
}
}
</script>
<body>
<input type="text" name="min" id="min" class="mini" onkeydown="return keypress(event)" placeholder="Enter the Min">
<input type="text" name="max" id="max" onkeydown="return keypress(event)" placeholder="Enter the Max">
</body>
DEMO: https://jsfiddle.net/efoc/dtqfLp05/
I have updated your code-
keydown--> keyup
String.fromCharCode(e.keyCode)--> e.keyCode(used direct keycode)
Check it-
https://jsfiddle.net/dtqfLp05/1/

How to add forward slash automatically in keyup function

I'm having some field in which when the user types after 2nd alphabet, I need to add forward slash automatically.
Is this possible in jquery?
<input type="text" class="someclass"/>
$(document).on('keyup','.classname', function(){
var count = $(this).val();
if(count == 2)
{
// Need stuff here
}
});
You can use:
$(document).on('keyup','.someclass', function(){
var count = $(this).val().length;
if(count == 2 && e.keyCode != 8){
$(this).focus().val(function( index, value ) { return value + "/ " ; });
}
});
You could do this:
$(document).on('keyup', '.someclass', function(e) {
var count = $(this).val().length;
if (count == 2) {
$(this).val($(this).val() + "/");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="someclass" />

Phone mask with jQuery and Masked Input Plugin

I have a problem masking a phone input with jQuery and Masked Input Plugin.
There are 2 possible formats:
(XX)XXXX-XXXX
(XX)XXXXX-XXXX
Is there any way to mask it accepting both cases?
EDIT:
I tried:
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf1").mask("(99) 9999?-9999");
But it doesn't works as I would like.
The closest one was (xx)xxxx-xxxxx.
I would like to get (xx)xxxx-xxxx when I type the 10th number, and (xx)xxxxx-xxxx when I type the 11th. Is it posible?
Try this - http://jsfiddle.net/dKRGE/3/
$("#phone").mask("(99) 9999?9-9999");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 );
$(this).val( first + '-' + lastfour );
}
});
Here is a jQuery phone number mask. No plugin required.
Format can be adjusted to your needs.
Updated JSFiddle.
HTML
<form id="example-form" name="my-form">
<input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX">
</form>
JavaScript
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.which || e.charCode || e.keyCode || 0;
$phone = $(this);
// Don't let them remove the starting '('
if ($phone.val().length === 1 && (key === 8 || key === 46)) {
$phone.val('(');
return false;
}
// Reset if they highlight and type over first char.
else if ($phone.val().charAt(0) !== '(') {
$phone.val('('+$phone.val());
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
Actually the correct answer is on http://jsfiddle.net/HDakN/
Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete
$("#phone").mask("(99) 9999-9999?9");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 5 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );
var lastfour = last.substr(1,4);
var first = $(this).val().substr( 0, 9 );
$(this).val( first + move + '-' + lastfour );
}
});​
You need a jQuery plugin for the mask works as well.
-- HTML --
<input type="text" id="phone" placeholder="(99) 9999-9999">
<input type="text" id="telf1" placeholder="(99) 9999*-9999">
<input type="text" id="telf2" placeholder="(99) 9999?-9999">
-- JAVASCRIPT --
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<script>
$(document).ready(function($){
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf2").mask("(99) 9999?-9999");
});
</script>
You can use the phone alias with Inputmask v3
$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });
$(function() {
$('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });
});
<label for="phone">Phone</label>
<input name="phone" type="tel">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.numeric.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.date.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.phone.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/jquery.inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/phone-codes/phone.js"></script>
https://github.com/RobinHerbots/Inputmask#aliases
Using jQuery Mask Plugin there is two possible ways to implement it:
1- Following Anatel's recomendations:
https://gist.github.com/3724610/5003f97804ea1e62a3182e21c3b0d3ae3b657dd9
2- Or without following Anatel's recomendations:
https://gist.github.com/igorescobar/5327820
All examples above was coded using jQuery Mask Plugin and it can be downloaded at:
http://igorescobar.github.io/jQuery-Mask-Plugin/
var $phone = $("#input_id");
var maskOptions = {onKeyPress: function(phone) {
var masks = ['(00) 0000-0000', '(00) 00000-0000'];
mask = phone.match(/^\([0-9]{2}\) 9/g)
? masks[1]
: masks[0];
$phone.mask(mask, this);
}};
$phone.mask('(00) 0000-0000', maskOptions);
With jquery.mask.js
http://jsfiddle.net/brynner/f9kd0aes/
HTML
<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">
JS
// Function
function phoneMask(e){
var s=e.val();
var s=s.replace(/[_\W]+/g,'');
var n=s.length;
if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}
$(e).mask(m);
}
// Type
$('body').on('keyup','.phone',function(){
phoneMask($(this));
});
// On load
$('.phone').keyup();
Only jQuery
http://jsfiddle.net/brynner/6vbrqe6z/
HTML
<p class="phone">85999998888</p>
<p class="phone">8599998888</p>
jQuery
$('.phone').text(function(i, text) {
var n = (text.length)-6;
if(n==4){var p=n;}else{var p=5;}
var regex = new RegExp('(\\d{2})(\\d{'+p+'})(\\d{4})');
var text = text.replace(regex, "($1) $2-$3");
return text;
});
The best way to do this is using the change event like this:
$("#phone")
.mask("(99) 9999?9-9999")
.on("change", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999
$(this).val( first + '-' + lastfour );
}
})
.change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.
The best way to do it on blur is:
function formatPhone(obj) {
if (obj.value != "")
{
var numbers = obj.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
obj.value = '';
upto = numbers.length;
if(numbers.length < 10)
{
upto = numbers.length;
}
else
{
upto = 10;
}
for (var i = 0; i < upto; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
}
As alternative
function FormatPhone(tt,e){
//console.log(e.which);
var t = $(tt);
var v1 = t.val();
var k = e.which;
if(k!=8 && v1.length===18){
e.preventDefault();
}
var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
e.preventDefault();
}
else{
setTimeout(function(){
var v = t.val();
var l = v.length;
//console.log(l);
if(k!=8){
if(l<4){
t.val('+7 ');
}
else if(l===4){
if(isNaN(q)){
t.val('+7 (');
}
else{
t.val('+7 ('+q);
}
}
else if(l===7){
t.val(v+')');
}
else if(l===9){
t.val(v1+' '+q);
}
else if(l===13||l===16){
t.val(v1+'-'+q);
}
else if(l>18){
v=v.substr(0,18);
t.val(v);
}
}
else{
if(l<4){
t.val('+7 ');
}
}
},100);
}
}
I was developed simple and easy masks on input field to US phone format jquery-input-mask-phone-number
Simple Add jquery-input-mask-phone-number plugin in to your HTML file and call usPhoneFormat method.
$(document).ready(function () {
$('#yourphone').usPhoneFormat({
format: '(xxx) xxx-xxxx',
});
});
Working JSFiddle Link https://jsfiddle.net/1kbat1nb/
NPM Reference URL https://www.npmjs.com/package/jquery-input-mask-phone-number
GitHub Reference URL https://github.com/rajaramtt/jquery-input-mask-phone-number
If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.
The cleanest way:
var options = {
onKeyPress: function(phone, e, field, options) {
var masks = ['(00) 0000-00000', '(00) 00000-0000'];
var mask = (phone.length>14) ? masks[1] : masks[0];
$('.phone-input').mask(mask, options);
}
};
$('.phone-input').mask('(00) 0000-00000', options);
Yes use this
$("#phone").inputmask({"mask": "(99) 9999 - 9999"});
Link here
$('.phone').focus(function(e) {
// add mask
$('.phone')
.mask("(99) 99999999?9")
.focusin(function(event)
{
$(this).unmask();
$(this).mask("(99) 99999999?9");
})
.focusout(function(event)
{
var phone, element;
element = $(this);
phone = element.val().replace(/\D/g, '');
element.unmask();
if (phone.length > 10) {
element.mask("(99) 99999-999?9");
} else {
element.mask("(99) 9999-9999?9");
}
}
);
});

Categories

Resources