I have the following code: http://jsfiddle.net/ntywf/1987/
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
}));
});
});
what I want is to remove the "-" sign off when it is inserted. what happens is that the cursor is always the last decimal home. I just want this code not to let the user enter negative numbers. How can I do this? (the problem is to move the cursor within the input, since it is always sent to the last character)
You can use a KeyCode (Link) to verify what key you pressed, and use replace to remove it:
$('input').keyup(function(e) {
var code = e.keyCode || e.which;
if(code == 109 || code == 189) { //Enter keycode
//Do something
var valor = $(this).val();
$(this).val(valor.replace(/[-]/g, ''))
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>
Here what I have tried.
JS
$('input').keyup(function() {
var $th = $(this).val();
$th = $th.replace(/[-]/g, "");
$(this).val($th)
console.log( $(this).val());
});
It will remove - sign from data.
This should solve your problem
What I have done is:
I have used the inbuilt HTML input field method setSelectionRange(), which sets the start and end positions of the current text selection in an element. (From MDN)
MDN Reference : https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
JS Code:
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
} ) );
$('input')[0].setSelectionRange(0, 0); //this method sets the range to zero text starting from 0 index to 0 index
});
});
JSFiddle: http://jsfiddle.net/dreamweiver/ntywf/1998/
Use type = "numeric" and min="0" This way you can prevent your text-field from accepting alphabets as well. min=0 will always make sure that it will never accept -ve value.
<input type="number" min="0"/>
JSFIDDLE DEMO will be helpful to you.
Related
I would like to disallow the user to type comma or dot while typing in the input field of the type number.
I have already searched and found solution, but it does not work.
If I type e.g. point, no matter which of the two solutions below, the input field is cleared.
This is my input field
<input type="number" class="form-control numbersOnly" name="angebot" id="angebot" min="1" step="1" placeholder="<?php the_field('language_shop_detail_button_counter_offer_placeholder', 'option'); ?>">
Those are the 2 approaches that don't work.
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
and
$('.angebotAbgebenContainer #angebot').keyup(function(event) {
var current = $(".angebotAbgebenContainer #angebot").val();
console.log("current", current);
var replaced = current.replace(/\./g, "");
console.log("replaced", replaced);
//replaced = parseInt(replaced);
// $('.angebotAbgebenContainer #angebot').val(replaced);
});
Those are the 2 approaches that don't work. As soon as I make a point, in both approaches, the input field is cleared.
But what I want is, if someone tries to type a point or a comma, it doesn't appear and if someone copy pastes a number, the comma and point must also be gone.
This works for me
Note it is type text
$('#angebot').on("input",function(event) {
var current = $(this).val();
console.log("current", current);
var replaced = current.replace(/[\D\.,]/g, "");
console.log("replaced", replaced);
$(this).val(replaced);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" id="angebot" />
If you are going to input numeric values in the input only, might as well disable the inputting of all keys except numeric, like:
$(document).on("keypress keyup blur", ".numbersOnly", function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
Where 48 - 57 represents keycodes, you can find all keycodes here.
Can use prevent default as below, and on change for paste
$(function() {
$('#angebot').on('keydown', function(e) {
if (e.keyCode == 188 || e.keyCode == 110) { // 188 for comma, 110 for point
e.preventDefault();
}
}).on('change', function() {
var self = $(this);
self.html( self.html().replace(new RegExp(',', 'g'),'') ); // Remove all commas.
self.html( self.html().replace(new RegExp('.', 'g'),'') ); // Remove all points
});
})
I am using a JS solution to allow letters and backspace only.
I want to add more options to the input, but can't see to find the right solution.
My Code:
<input id="inputTextBox">
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
console.log(inputValue);
});
});
This give me the correct result of only letter input and use of backspace.
For the correct user experiece I need to add the following.
Allow input '?' , '*' and 'spacebar'.
And if possible, change the input in the form when the user typ.
So if a user typ a '?' or 'spacebar', it changes into the value '*' automatic.
Thanks in advance.
Slightly modified from this solution:
How to allow only numeric (0-9) in HTML inputbox using jQuery?
EDIT: added code to preserve position when ? and spaces are replaced
// Restricts input for the set of matched elements to the given inputFilter function.
// Modified to pass element to callback function
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
$(document).ready(function(event) {
$("#inputTextBox").inputFilter(function(el) {
var oldSelectionStart = el.selectionStart;
var oldSelectionEnd = el.selectionEnd;
var oldValue = el.value;
el.value = el.value.replace(/[* ]/g, '?'); //replace * space with ?
el.value = el.value.replace(/[^a-zA-Z?]/g, '');
if (oldValue != el.value)
el.setSelectionRange(oldSelectionStart-(oldValue.length-el.value.length), oldSelectionEnd-(oldValue.length-el.value.length));
return /^[a-zA-Z?]+?$/.test(el.value); // alphabet question only
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputTextBox">
Simply added a keyup function to replace the character '?' and space to *
and also added envent ids of space and '?' in your keypress function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputTextBox">
<script>
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0 && inputValue != 63 && inputValue != 42 && inputValue != 32)) {
event.preventDefault();
}
});
$("#inputTextBox").keyup(function(){
var inputTxt = $('#inputTextBox').val();
inputTxt = inputTxt.replace('?', '*').replace(' ', '*')
$('#inputTextBox').val(inputTxt);
});
});
</script>
You have an issue with your code already since the 65 - 123 contains letters, but it also contains [] _ to name a few.
so you probably want 65-90 for A-Z then 97-122 for a-z 48-57 for 0-9. then check each character you want to allow, they probably wont be in a range.
If you look at the ascii chart here https://theasciicode.com.ar/ascii-printable-characters/question-mark-ascii-code-63.html you will see all the numbers you need to include (or exclude)
On the keyUp event, you could look at the value and then change the last character to the * if you wish, but remember that will change the actual value, not just mask it.
If you want it masked, you should use an <input type="password"> field, which has that behaviour by default.
I am using the following JavaScript function to add thousand separator for a input number on keyup event.
$("#inputId").on('keyup', function(evt){
if (evt.which != 110 && evt.which != 190){
var n = parseFloat($(this).val().replace(/\,/g,''),10);
$(this).val(n.toLocaleString());
}
});
Most of the cases this function is working as expected, but the only issue is the input field does not accept zero after the decimal point (for example 10.01) but it does accept numbers like 10.25 . I can't figure out the reason for this behavior. Any idea?
Thanks.
Splitting on the decimal would work. Something like this. Note this is very basic starting point and does not account for the different separators in other countries/systems (ie: 10.000,00)
<script>
var myinput = document.getElementById('myinput');
myinput.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
</script>
<input id="myinput" type="text'>
I have a calculator I'm working on and came across a problem. To combat so that users can't leave a field blank, I'm forcing a zero if the field is left empty. That's all fine, but the problem is that when the text in the field is deleted to remove the zero and enter a new number, it automatically enters zero so my new number looks like this: 05
How do i run a replace where if there is more than 2 places in the number and the first number is zero, replace the zero? Here's the code i'm using for my calculator.
$(function(){
calculate();
$('.input').keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
$('.input').on('keyup',function(){
if($(this).val()==''){
$(this).val('0');
}
calculate();
});
});
function calculate(){
var d6 = parseFloat(($('#d6').val()).replace(/,/g,''));
var d20 = parseFloat(($('#d20').val()).replace(/,/g,''));
var b20 = d6;
var e20 = parseFloat(($('#e20').val()).replace(/,/g,''));
var f20 = d20*e20;
var f22 = b20/f20;
var f23 = (52-f22)*f20;
$('#f20').html(formatCurrency(f20));
$('#f22').html(f22.toFixed(2));
$('#f23').html(formatCurrency(f23));
}
function formatCurrency(x) {
return '$'+x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
If you are essentially trying to turn it into a formatted number you could try type coercion:
'' + new Number('') // "0"
'' + new Number('0') // "0"
'' + new Number('05') // "5"
'' + new Number('0000.2') // "0.2"
Change the zeroing code to use the blur() event, i.e when the field loses focus.
$('.input').blur(function(){
if($(this).val()=='')
{
$(this).val('0');
}
});
I'm assuming that the text is removed from pressing the backspace key.
If that is the case then you keyup handler would fire when you backspace on the zero, which would detect no input, then add the zero.
First of all, you are doing it a hard way. And try this... if the user clicks on the input then it will be cleared and the user can write whatever number he wants...
$( ".input" ).focus(function() {
(this).val('');
});
In case you are using an HTML5 form you can avoid that piece of code like this:
<input type="number" placeholder="Type a number" required>
The required attribute is a boolean attribute.
When present, it specifies that an input field must be filled out.
Instead of using keyup and keypress event for checking and replacing blank to zero, use change event.
$(function(){
calculate();
$('.input').keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
$('.input').on('keyup',function(){
calculate();
});
$('.input').on('change',function(){
if($(this).val()==''){
$(this).val('0');
}
});
});
function calculate(){
var d6Val = ($('#d6').val() !== "")? $('#d6').val() : '0';
var d20Val = ($('#d20').val() !== "")? $('#d20').val() : '0';
var e20Val = ($('#e20').val() !== "")? $('#e20').val() : '0';
var d6 = parseFloat((d6Val).replace(/,/g,''));
var d20 = parseFloat((d20Val).replace(/,/g,''));
var b20 = d6;
var e20 = parseFloat((e20Val).replace(/,/g,''));
var f20 = d20*e20;
var f22 = b20/f20;
var f23 = (52-f22)*f20;
$('#f20').html(formatCurrency(f20));
$('#f22').html(f22.toFixed(2));
$('#f23').html(formatCurrency(f23));
}
function formatCurrency(x) {
return '$'+x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
One more thing. Change event only fires when you focus-out from that input.
Please let me know if you will face any issue.
I would like to have an input that would change to upper case on keyup. So I attach a simple event on keyup.
HTML
<input id="test"/>
Javascript (with jQuery)
$("#test").keyup(function(){
this.value = this.value.toUpperCase();
});
But I found that in Chrome and IE, when you push left arrow, the cursor automatically move to end. I notice that I should detect if the input is letter only. Should I use keycode range or regexp for detection?
Example: http://jsbin.com/omope3
Or you can use the following (this is probably faster and more elegant):
<input style="text-transform: uppercase" type='text'></input>
But that sends the as-typed value back in the form data, so use either of the following to store it as all-caps in the database:
MySQL: UPPER(str)
PHP: strtoupper()
Another solution, if you use the text-transform: uppercase; css property:
<input id='test' style='text-transform: uppercase;' type='text'></input>
And with jQuery help you choose the blur event:
$("#test").blur(function(){
this.value = this.value.toUpperCase();
});
With this solution, you don't have to upper the database fields, you can use the cursor for movement and the user can insert/rewrite the text in the input field.
Use this:
<input onkeyup="MakeMeUpper(this)" type="text"/>
And in your JS Code Part put:
function MakeMeUpper(f, e){
var actualValue = f.value;
var upperValue = f.value.toUpperCase();
if( actValue != upperValue){
f.value = upperValue;
}
}
This code won't change the text if the user entered something that is not text (left or right arrow).
Yeah, looks like some browsers move the cursor to the end when the value gets updated. You could do this:
$("#test").keyup(function(){
var upper = this.value.toUpperCase();
if (this.value != upper)
this.value = upper;
});
which will only change the value if it needs to be changed. However, that still leaves you with the problem that if you type abd, move left, hit c to get abcd, the cursor will still get moved to the end.
Javascript (with jQuery)
$("#test").keyup(function(){
$(this).val($(this).val().toUpperCase());
});
var str = $(this).val();
if (evt.keyCode != 37 && evt.keyCode != 39)
{
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
$(this).val(str);
}
You probably want to look at keyCode in your keyup function.
var UP_ARROW = 38,
DOWN_ARROW = 40;
$('#test').keyup(function(evt){
if (evt.keyCode == UP_ARROW)
{
this.value = this.value.toUpperCase();
}
if (evt.keyCode == DOWN_ARROW)
{
this.value = this.value.toLowerCase();
}
});