I validate an input field by those patterns:
only positive numbers
only one .
only numeric values
only two decimals after .
only numbers between 0 and 100
limit input to 5 characters (0 ... 1.1 ... 10.2 ... 33.23 ... 99.99 or 100)
These validations work with my code fine. Even there is a better way to code this validation. But anyways - my issue, which I can't solve right now is - if I enter a value for example 99.99 or 100 or 23.23 and I want to change the value again by selecting / mark the entire value with my mouse for example - it will not change! If I write 2.33 and I select/mark the entire value with my mouse it will change. So it seems I'm facing a 'false' state which does not allow me to enter another digit and right now I could not find a kind of an event which detects that I select something in my input field.
I have prepared an JSFIDDLE code - where do I have my confusion?
ps: I am also aware that maybe my keypress event is overwriting the false/true states, I'm trying to solve this afterwards.
Thank you very much!
Best Regards
$('#inpNumber').on('input', function() {
var inpVal = $(this).val();
if ( inpVal > 100 || inpVal < 0 || !inpVal) {
$( "#inpNumber" ).removeClass( "is-valid" );
$( "#inpNumber" ).addClass( "is-invalid" );
} else {
$( "#inpNumber" ).removeClass( "is-invalid" );
$( "#inpNumber" ).addClass( "is-valid" );
}
});
$('#inpNumber').keypress(function (event) {
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
return false;
}
return isNumberRegChecked(event, this);
return isNumber(event, this);
});
function isNumberRegChecked( evt, element ) {
var inpVal = $(element).val();
// ^(\d\d?(\.\d\d?)?|100(\.00?)?)$ also possible
var checkShare = /^(\d{0,2}(\.\d{0,2})?)$/.test(inpVal);
if (checkShare == false)
return false;
return true;
}
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function isNumber( evt, element ) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}
Related
I have following jQuery script implemented which suppose to restrict input in input form.
<script language="JavaScript">
var inputPlz = $j( "span#spanvertragsnehmer_plz input.plz" );
function attachEventHandlerToInputNumber(input)
{
input.on("keypress", function(key)
{
if ((key.which != 8 && key.which != 0 && (key.which < 48 || key.which > 57)) || inputPlz.val().length > 4)
{
return false;
}
});
}
attachEventHandlerToInputNumber(inputPlz);
</script>
In the following code I can restrict the input but once it goes to 5 digit number I can't edit the number using backspace anymore. Is there anything I missing here ?? Thank you.
This statement || inputPlz.val().length > 4 causes the return false; line to execute whenever the input length is 5+, no matter what key is pressed. Backspace is a key like any other thus you cannot backspace after 5+ digits.
If you want to allow backspaces once 5+ digits have been entered you could change that segment to || (inputPlz.val().length > 4 && key.which != 8))
This question already has answers here:
Is it possible to get pasted text without using the setTimeout() function?
(4 answers)
Closed 8 years ago.
I have an input field like this
<input type ="number" id="numberTxt" placeholder="Number Only"/>
I am checking whether the value is a number or not and clearing back as the following function using keypress event
<script>
$(document).ready(function(numberTxt){
$('#numberTxt').keypress(function(event) {
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 45 && (charCode != 46 || $(this).val().indexOf('.') != -1) && (charCode < 48 || charCode > 57))
{
return false;
}
else
return true;
});
});
</script>
BUT when we copy paste some text (CTRL V CNTRL C) the above code is
not working
or that i tried this function below
but not getting the value of the input at that point
its "" (empty string).
when we copy paste its correctly triggering this function.
<script>
$(document).ready(function(){
$('#numberTxt').on("paste",function('numberTxt') {
var val = $('#numberTxt').val() ;
});
});
</script>
Is the any another way to get the input tag's value with event ,
if i pass the event like the keypress function before
any other Suggestions or answers to check number during copy paste will also be helpful
One might well feel below function correct using .bind('input'.....
http://jsfiddle.net/pxfunc/KDLjf/ got this one from
Is it possible to get pasted text without using the setTimeout() function?
This is how you validate only integer value on PASTE
$('#numberTxt').on("paste",function(e) {
var $this = $(this);
setTimeout(function(){
var val = $this.val(),
regex = /^[\d]+$/;
if( regex.test(val) ){
$this.val( val );
}
else{
$this.val('');
}
alert(val);
},0);
});
DEMO: http://jsfiddle.net/jogesh_pi/LaN8f/1/
How to disable special characters from paste in a textbox?
Im using a onkeypress event handler
function disableOtherChar(evt) {
var charCode;
charCode = (evt.which) ? evt.which : evt.keyCode;
var ctrl;
ctrl = (document.all) ? event.ctrlKey : evt.modifiers & Event.CONTROL_MASK;
if ((charCode > 47 && charCode < 58) || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || charCode == 9 || charCode == 45 || (ctrl && charCode == 86) || ctrl && charCode == 67) {
return true;
} else {
$(":text").live("cut copy paste", function (e) {
e.preventDefault();
});
return false;
}
}
But it doesnt block special characters when pasting, only in entering,
suppose that you have a Input
<input id="textInput" name="textInput">
and you have the following script to validate the copy:
$(function(){
$( "#textInput" ).bind( 'paste',function()
{
setTimeout(function()
{
//get the value of the input text
var data= $( '#textInput' ).val() ;
//replace the special characters to ''
var dataFull = data.replace(/[^\w\s]/gi, '');
//set the new value of the input text without special characters
$( '#textInput' ).val(dataFull);
});
});
});
You could use a 3rd party plugin like jquery.alphanum, it works for paste (ctrl+v) too.
The code looks like this :
$("input").alphanum();
Or you could use it in a more spceficied way like this :
$("#elemet").alphanum({
allow : "asd",
disallow : "!##",
allowUpper : false
});
The above code you need to add it into your JQuery declaration.
I mention the fact that you can also modify the blacklist array from the script jquery.alphanum.js on line 124. You will find a function name getBlacklistAscii, in that you modify var blacklist = ... to what suits you.
Not an answer, just a comment regarding:
var ctrl;
ctrl = (document.all) ? event.ctrlKey:evt.modifiers & Event.CONTROL_MASK;
Please learn to use feature detection, inferring behaviour based on object inference is doomed to fail at least some of the time.
Also, don't use the key code, test the actual characters. E.g if you just want to allow letters, numbers and few others:
function hasInvalidChars(s) {
// allow letters, spaces, numbers only
var validChars = /[\w\s\d]/gi;
var x = s.replace(validChars, '');
return !!x.length;
}
alert(hasInvalidChars('asdf1234 1234asd')); // false
alert(hasInvalidChars('asdf1.234 1234asd')); // true
Expand the set of valid characters to whatever you want.
Oh, if you want it as a one–liner:
function hasInvalidChars(s) {
return !!s.replace(/[\w\s\d]/gi, '').length;
}
I have changed a bit the script provided by Christian.
This version replaces everything that is not between spaces (ASCII DEC 32) to tilde (ASCII DEC 126) and whitespace characters. Meaning all characters that are not-visible should be removed.
If you add the class api_clean_characters in a Jquery environment this should work out of the box.
<textarea class="api_clean_characters"></textarea>
$(function(){
$( ".api_clean_characters" ).bind( 'paste',function(ev)
{
var $target = $(ev.target);
setTimeout(function()
{
//get the value of the input text
var data= $target.val() ;
//replace the special characters to ''
var dataFull = data.replace(/[^ -~\s]/gi, '');
//set the new value of the input text without special characters
$target.val(dataFull);
});
});
});
I am a newbie to jquery and javascript so this may be a silly question
I have a textfield and i would like to filter the input
so it will only let the usesr enter in [A-Z] chacters and also if the length of [A-Z] has reached 3 it then also disables the user from entereing any more characters
You need a function that "monitors" the input field. Something like:
$('#yourfield').change(function() {
$val = $(this).val();
if($val.length() > 2) $(this).attr('disabled', true)
// so on, just to give you some ideas
});
http://jsfiddle.net/GLXuv/7/
$('#sexyInput').keyup(function() {
$(this).val($(this).val().replace(/[^A-Za-z]/g, ''));
if($(this).val().length >= 3) $(this).prop('disabled', true);
});
There are two ways an input form can be populated by a user:
User types in the form.
User pastes in the form.
This requires binding two separate events:
$('.numbers-only').keypress(function(e) {
// Allow only keys [A-Za-z] and enter
if (e.which !== 13 && ((e.which < 65 || e.which > 90) && (e.which < 97 || e.which > 122)) ) {
e.preventDefault();
}
}).bind('paste', function() {
var el = this;
setTimeout(function() {
// replace anything that isn't a number with ''
$(el).val($(el).val().replace(/[^A-Za-z]/g, ''));
}, 100);
});
I have a simple text box and I am entering number value to this.And i want to format the number value to two decimal places.Like If i enter the 10 in the text box and after pressing entering or leaving textbox it should be converted into 10.00.Please tell me if there exist any possibility to do this using javascript or vb.net or asp.net property of textbox.I already tried in JavaScript on enter key or tab key press but it convert it into 10.00 each time when i press the enter or tab.here is code
//Make Formatting with .00
document.onkeydown = function disableKeys() {
if( typeof event != 'undefined' ) {
if( (event.keyCode == 9) ||
(event.keyCode == 13) ) {
var a;
var b;
a=parseFloat(document.getElementById('txtpkrusd').value,10);
b=parseFloat(document.getElementById('txtRatelb').value,10);
document.getElementById('txtpkrusd').value=formatNumber(a);
document.getElementById('txtRatelb').value=formatNumber(b);
}
};
};
var num = 10;
var result = num.toFixed(2); //will give 10.00
Examples
hiya hope this helps: (apart from my comment above i.e. to round use .toFixed(num))
demo (enter the number and press enter) : http://jsfiddle.net/6wG26/5/ OR Enter and Tab keys both here http://jsfiddle.net/Mtw7c/7/
Please; let me if this is not what you want I will delete my post; but this will help you.
Since you dint had much code up I have made forked sample here:
**HTML:**
<input type="text" name="one" class="currency">
**JQuery code:**
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
$( function() {
$('.currency').currencyFormat();
});
OR ENter key & Tab key here: http://jsfiddle.net/Mtw7c/7/
$('.currency').live('keydown', function(e) {
var key = e.keyCode || e.which;
if (key== 9 || key == 13) {
e.preventDefault();
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
// call custom function here
}
});
hope this helps and it will be good if you read the following link - sample taken from here but to make it sample for you, In jQuery, what's the best way of formatting a number to 2 decimal places?
You can always put validation for the number only text box & other amendments, Hope this helps mate, cheers!!