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/
Related
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 "."
I want to show format of the phone number in the form as a placeholder and not get erased as the user types the number.
html placeholder dissapears as the user types. I want the placeholder to stay and lead the user as they type phone number.
<form action="payonline.html">
<input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required placeholder="___ - ___ - ____ ">
<input type="submit" value="Submit">
</form>
I think you need to use onkeypress and onkeyup event in javascript to create a phone input more user friendly.
You can use code below.Im not sure you using jquery so i use pure javascript.
<form action="payonline.html">
<input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required placeholder="___ - ___ - ____ " onkeypress="validate_int(this)" onkeyup="phone_number_mask()">
<input type="submit" value="Submit">
</form>
<script>
function validate_int(myEvento) {
if ((myEvento.charCode >= 48 && myEvento.charCode <= 57) || myEvento.keyCode == 9 || myEvento.keyCode == 10 || myEvento.keyCode == 13 || myEvento.keyCode == 8 || myEvento.keyCode == 116 || myEvento.keyCode == 46 || (myEvento.keyCode <= 40 && myEvento.keyCode >= 37)) {
dato = true;
} else {
dato = false;
}
return dato;
}
function phone_number_mask() {
var myMask = "___-___-____";
var myCaja = document.getElementById("phone");
var myText = "";
var myNumbers = [];
var myOutPut = ""
var theLastPos = 1;
myText = myCaja.value;
//get numbers
for (var i = 0; i < myText.length; i++) {
if (!isNaN(myText.charAt(i)) && myText.charAt(i) != " ") {
myNumbers.push(myText.charAt(i));
}
}
//write over mask
for (var j = 0; j < myMask.length; j++) {
if (myMask.charAt(j) == "_") { //replace "_" by a number
if (myNumbers.length == 0)
myOutPut = myOutPut + myMask.charAt(j);
else {
myOutPut = myOutPut + myNumbers.shift();
theLastPos = j + 1; //set caret position
}
} else {
myOutPut = myOutPut + myMask.charAt(j);
}
}
document.getElementById("phone").value = myOutPut;
document.getElementById("phone").setSelectionRange(theLastPos, theLastPos);
}
</script>
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
Is there a way to limit the number of letters and numbers allowed to type in to an input field? I would like to only allow 3 letters and 2 numbers to be typed in, in whatever order.
Is this possible using the jQuery Mask Plugin? Or not?
See my jsFiddle here: http://jsfiddle.net/0akoL2x2/
html:
<input type="text" class="preview" size="30" placeholder="Preview text" class="text-input" maxlength="5" autofocus />
jquery:
jQuery('.personalisation').mask("XXXZZ", {
translation: {
'X': {pattern: /[A-Za-z0-9]/},
'Z': {pattern: /[A-Za-z0-9]/},
}
How about using a data attribute? Let's call it data-temp:
<input type="text" class="alnum" maxlength="5" data-temp="">
Use $(document).on('input'... to monitor all changes (even dynamic elements), and revert back immediately if the new value exceeds the maximum. Otherwise, let it happen, and update data-temp to this new value.
$(document).on('input', '.alnum', function(){
var txt = $(this).val();
if(
txt.replace(/[^0-9]/g,"").length > 2 ||
txt.replace(/[^A-Za-z]/g,"").length > 3 ||
txt.replace(/[a-zA-Z0-9]/g,"").length != 0
){
$(this).val( $(this).data('temp') );
return;
}
$(this).data('temp', txt);
});
JSFiddle demo
Here is a fiddle that works:
http://jsfiddle.net/igorshmigor/k2ss62gg/3/
The JS code looks like this:
var numberCountLimit = 2;
var letterCountLimit = 3;
$(document).ready(function() {
$('.preview').keypress(function(key) {
if (key.charCode == 0){
return true;
}
var current = $(this).val();
var filtered = current.replace(/[^a-z0-9]/gmi,'');
$(this).val(filtered);
var digits = filtered.replace(/[^0-9]/gmi,'');
var alpha = filtered.replace(/[^a-z]/gmi,'');
var digitCount = digits.length;
var alphaCount = alpha.length;
var isNumber = false;
var isAlpha = false;
if (key.charCode > 47 && key.charCode < 58){
isNumber = true;
if (digitCount >= numberCountLimit){
return false; // too many digits
}
}
if (key.charCode > 64 && key.charCode < 123){
isAlpha = true;
if (alphaCount >= letterCountLimit){
return false; // too many letters
}
}
if (!isAlpha && !isNumber){
return false;
}
});
});
P.S.: I don't think this can be done with just the jQuery Mask Plugin.
Give your text box an ID.
$("#box").mask('XXXZZ', {'translation': {
X: {pattern: /[A-Za-z0-9]/},
Z: {pattern: /[A-Za-z0-9]/}
}
});
JSFiddle
How about this, you hook the keypress and check the number/letter counters and if it exceeds you will just ignore the keypress (by returning false)
var numberCount = 0;
var numberCountLimit = 2;
var letterCount = 0;
var letterCountLimit = 3;
$(document).ready(function() {
$('.personalisation').keypress(function(key) {
var currentText = $(this).val();
numberCount = 0;
letterCount = 0;
for (var i = 0, len = currentText.length; i < len; i++) {
if(currentText.charCodeAt(i) < 48 || currentText.charCodeAt(i) > 57) {
//Is number
if((numberCount+1) > numberCountLimit) {
return false;
}
numberCount++;
} else {
//Is letter
if((letterCount+1) > letterCountLimit) {
return false;
}
letterCount++;
}
}
return true;
});
}
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/