Is it possible to translate this jquery code into javascript?
$("#field").keypress(function (evt) {
if (evt.which == 46) {
$(this).val($(this).val() + ',');
evt.preventDefault();
}
//The input of more than 2 numbers after the decimal point is prevented
var foo = $(this).val();
if( !foo.match(/^(\d)*,?(\d){0,1}$/) ){
evt.preventDefault();
}
});
jsfiddle
Thanx in advance!
Finally i have found a solution. Hope it helps anybody
<script type="text/javascript">
function decimals(that) {
var s = that.value;
var i = s.indexOf(".");
if (i < 0 || s.substr(i+1).length < 2) return;
alert("Only 1 digit to the right of the decimal are allowed!");
that.value = s.substring(0,i+2);
}
</script>
<input type="text" size="5" maxlength="5" onkeyup="decimals(this)">
best wishes
check this code http://jsfiddle.net/s62W5/ may help you
var x=document.getElementById("field");
x.onkeydown = function(e){
var keyPress;
if (typeof event !== 'undefined') {
keyPress = event.keyCode;
}
else if (e) {
keyPress = e.which;
}
if (keyPress == 46) {
x.value= x.value + ',';
}
};
Related
I have one textbox.It should be allow only decimal numbers and after dot only allow two digit(example 34545.43). how we can do it using jquery i have searched in google and stackoverflow but not satisfied answer because some script is not working in chrome and firefox. I tried but it is not working properly.So need help how to do it.http://jsfiddle.net/S9G8C/1685/
Js:
$('.allow_decimal').keyup(function (evt) {
var self = $(this);
self.val(self.val().replace(/[^0-9\.]/g, ''));
if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) {
evt.preventDefault();
}
});
This jQuery function will round the value on blur event of textbox
$.fn.getNum = function() {
var val = $.trim($(this).val());
if(val.indexOf(',') > -1) {
val = val.replace(',', '.');
}
var num = parseFloat(val);
var num = num.toFixed(2);
if(isNaN(num)) {
num = '';
}
return num;
}
$(function() { //This function will work on onblur event
$('#txt').blur(function() {
$(this).val($(this).getNum());
});
});
Number: <input type="text" id="txt" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can directly remove the 3rd digit when the user enters that.
var txt = document.getElementById('txtId');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
}
<input id="txtId" type="text"></input>
I would like to allow the users to put only one kind of symbol (character) in input and only at the beginning of string.
Of course on keyDown/keyUp event. I'm looking-for the fastest solution.
Supposing you have an input like
<input type="text" id="text">
you can use the following code
$(function(){
var alreadyIn = 0;
var chars = [33, 64, 35]; // Place here the codes for accepted chars (!##$ etc)
$("#text").on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(chars.indexOf(code) != -1) {
if($(this).caret() != 0){return false;}
if(alreadyIn){return false;}
alreadyIn++
} else {
if(alreadyIn && $(this).caret() == 0){return false;}
}
return true;
}).on('keyup', function(e){ // Keyup event to catch backspace and delete
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 8 || code == 46) {
var current = $(this).val();
var instances = 0;
chars.forEach(function(char) {
if(current.search(String.fromCharCode(char)) > -1){instances++;}
});
alreadyIn = instances == 0 ? 0 : 1;
}
}).bind("cut copy paste", function(e) { // Do not allow cut copy paste in field
e.preventDefault();
});
});
EDIT
I've updated the answer. You have to include jquery caret plugin also. You can find it here
How can i create a increment/decrement text box in HTML Page using jquery or Javascript....
and also i want to set maximum and minimum values....
How to i achieve this?
Simple :)
HTML :
<div id="incdec">
<input type="text" value="0" />
<img src="up_arrow.jpeg" id="up" />
<img src="down_arrow.jpeg" id="down" />
</div>
Javascript(jQuery) :
$(document).ready(function(){
$("#up").on('click',function(){
$("#incdec input").val(parseInt($("#incdec input").val())+1);
});
$("#down").on('click',function(){
$("#incdec input").val(parseInt($("#incdec input").val())-1);
});
});
did you try input type="number"?
Just try
<input type="number" name="points" step="1">
that's it.
In the step, you can enter any value you want. And the arrows will move that many steps on clicking.
Have a look here. I have also used it.
numeric-up-down-input-jquery
I think you can use jquery ui spinner . For a demo take a look at the link here
Try this Spinner Control. hope this will help you.
http://www.devcurry.com/2011/09/html-5-number-spinner-control.html
JavaScript (JQuery) of increment and decrement for both ( - and + ) ##
$(document).ready(function () {
$('#cost').w2form ({
name : 'cost',
style : '',
fields : [
{
name : 'amount',
type : 'int'
}
]
});
$("#amount").keydown(function (e) {
var key = e.keyCode;
if (key == 40) {
if ( $(this).val() != "") {
$(this).val();
} else {
$(this).val("0");
w2ui['cost'].record[$(this).attr('name')] = "0";
w2ui['cost'].refresh();
}
}
});
}
HTML
<html>
<form>
<label>Amount</label>
<input type="text" id="amount" name="amount" style= "width: 140px"/>
</form>
</html>
function incerment(selector, maxvalue){
var value = selector.val() != undefined ? parseInt(selector.val()) : 0;
var max_value = maxvalue != undefined ? parseInt(maxvalue) : 100;
if(value >= max_value){
return false;
} else {
selector.val(++value);
}
}
function decrement(selector, minvalue){
var value = selector.val() != undefined ? parseInt(selector.val()) : 0;
var min_value = minvalue != undefined ? parseInt(minvalue) : 1;
if(value <= min_value){
return false;
} else {
selector.val(--value);
}
}
//MAXIMUM/MINIMUM QUANTITY
$('#up').click(function(){
incerment($("#incdec input"));
return false;
});
$('#down').click(function(){
decrement($("#incdec input"));
return false;
});
Start of arrow keyup and keydown by JavaScript (JQuery)
$("#amount").on('keydown', function (event) {
//up-arrow
if (event.which == 38 || event.which == 104) {
$(this).val((parseInt($(this).val()) + 1));
//down-arrow
} else if (event.which == 40 || event.which == 98) {
$(this).val((parseInt($(this).val()) - 1));
}
});
JavaScript
function forKeyUp(value,e){
e = e || window.event;
if (e.keyCode == '38' || e.keyCode == '104') {
if(parseInt(value)<1000){
value=(parseInt(value) + 1);
var id = $(e.target).attr('id');
$("#"+id).val(value);
}
}
else if (e.keyCode == '40' || e.keyCode == '98') {
if(parseInt(value)>0){
value=(parseInt(value) - 1);
var id = $(e.target).attr('id');
$("#"+id).val(value);
}
}}
//Call function
$("#amount")..on('keydown', function (event) {
forKeyUp($(this).val(),event);
});
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");
}
}
);
});
I have an input field which I want to restrict so that the user only can input a number with the maximum of two decimals. Want to do this using jQuery.
Could I use jQuery toFixed() function somehow?
Thanx!
An alternative approach with a regular expression:
$('#id').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
The id selector can be replaced by a css selector.
$('input#decimal').blur(function(){
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
if(num/cleanNum < 1){
$('#error').text('Please enter only 2 decimal places, we have truncated extra points');
}
});
Here is a fiddle http://jsfiddle.net/sabithpocker/PD2nV/
Using toFixed will anyhow cause approximation 123.6666 -> 123.67
If you want to avoid approximation check this answer Display two decimal places, no rounding
A HTML5 solution:
<input type="number" step="0.01" />
Demo
If you want to style invalid inputs (some browsers do it by default), you can use :invalid selector:
input:invalid { box-shadow: 0 0 1.5px 1px red; }
Note this approach won't attempt to truncate the number automagically, but if the user enters more than two decimal digits, the input will become invalid, and thus the form won't be submitted:
<input type="text" name="amount1" id="amount1" class="num_fld Amt" onkeypress="return check_digit(event,this,8,2);" size="9" value="" maxlength="8" style="text-align:right;" />
The following function will restrict decimals according to your need of decimal places and also restrict more than one dot
function check_digit(e,obj,intsize,deczize) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) { keycode = e.which; }
else { return true; }
var fieldval= (obj.value),
dots = fieldval.split(".").length;
if(keycode == 46) {
return dots <= 1;
}
if(keycode == 8 || keycode == 9 || keycode == 46 || keycode == 13 ) {
// back space, tab, delete, enter
return true;
}
if((keycode>=32 && keycode <=45) || keycode==47 || (keycode>=58 && keycode<=127)) {
return false;
}
if(fieldval == "0" && keycode == 48 ) {
return false;
}
if(fieldval.indexOf(".") != -1) {
if(keycode == 46) {
return false;
}
var splitfield = fieldval.split(".");
if(splitfield[1].length >= deczize && keycode != 8 && keycode != 0 )
return false;
}else if(fieldval.length >= intsize && keycode != 46) {
return false;
}else {
return true;
}
}
}
$("#myInput").focusout(function() {
if ($(this).val().length > 2 || isNaN(Number($(this).val())) {
alert("Wrong number format");
}
});
Try this for all symbols:
inputField.value.replace(/(\...)(.)/, "$1");
or this for numbers:
inputField.value.replace(/(\.[0-9][0-9])([0-9])/, "$1");
I found this method here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Example:_Switching_words_in_a_string
<input type="text" id="decCheck" onkeyup="decimalCheck();"/>
<script>
function decimalCheck(){
var dec = document.getElementById('decCheck').value;
if(dec.includes(".")){
var res = dec.substring(dec.indexOf(".")+1);
var kl = res.split("");
if(kl.length > 1){
document.getElementById('decCheck').value=(parseInt(dec * 100) /
100).toFixed(2);
}
}
}
</script>
A similar solution with a backspace hit on reaching more than 2 decimal places.
function limitDec(id) {
// find elements
var amt = $("#testdec")
// handle keyup
amt.on("keyup", function() {
if (isNaN(amt.val())) {
amt.val(0);
}
if (amt.val().indexOf(".") > -1 && (amt.val().split('.')[1].length > 2)) {
amt.val(amt.val().substring(0, amt.val().length - 1));
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" id="testdec" onkeyup="limitDec(this.id)" />