How to add forward slash automatically in keyup function - javascript

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" />

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 "."

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');
});

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

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/

textbox value with hard coded dash

I have a textbox in the page. <input type="text" id="cell">
I have used below jquery....
i = 0;
$(document).ready(function () {
$("#cell").keypress(function () {
i += 1;
if (i == 4) {
var cellValue = $("#cell").val() + "-";
$("#cell").val(cellValue);
}
});
});
whenever an user types 12345678 (or any number) it automatically shows 123-45678. But problem is when user uses backspace or delete and then starts typing 12345678 it does not show 123-45678. Please help
i should be the length of the value , not the number of times you pressed the key
Try this -
$("#cell").keypress(function () {
i = $(this).val().length;
if (i == 3) {
var cellValue = $("#cell").val() + "-";
$("#cell").val(cellValue);
}
});
Demo --> http://jsfiddle.net/KZmc9/2/
Try
$(document).ready(function(){
$("#cell").keypress(function(){
if (this.value.length == 3) {
$("#cell").val(this.value + "-");
}
});
});
Demo: Fiddle
I would split the input into two, because otherwise users have to delete the dash if they want to delete the 3rd number.
http://jsfiddle.net/TATnK/
$(document).ready(function() {
$('#cell_1').on('input', function(e) {
if($(this).val().length == 3) {
$('#cell_2').focus();
}
});
$('#cell_2').keyup(function(e) {
if(e.which == 8 && $(this).val().length == 0) {
$('#cell_1').focus();
}
});
});

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