When pasteing value into input area, can't capture value - javascript

I have a button and an input area. When the input's length is filled (14) - then the button's class will be active. That currently works, however, when the user pastes a value into the input area, the length is zero until the user enters something else. My goal is to display the active class on the button when the paste is done if the length of the value is 14.
JS
$('#number', '#form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
document.getElementById('number').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
HTML
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'>
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>

You should use the input event. This event is triggered when eve the input changes. keyup and keydown will fire even if the input hasn't changed. Pressing CTRL will trigger keydown even if nothing has changed. input will only be triggered if it has changed, ie: CTRL + V (paste)
$('#number', '#form')
.on('input', function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'>
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>

Also use another event input so it triggers your function on keydown and on input as well. Check out this working example using your code
$('#number', '#form').on('keydown input',function(){});
$('#number', '#form')
.on('keydown input', function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'><br /><br />
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>

Related

Need help restricting a js function(that restricts invalid chars) to a particular input type

Hi i would like to restrict a function that allows only, numbers, back space and left & right arrow keys to inputs with number type, because when i implement it, it also affects my text inputs.
<script>
function chars(evt){
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46
|| event.keyCode == 37 || event.keyCode == 39) {
return true;
}
else if ( key < 48 || key > 57 ) {
return false;
}
else return true;
}
</script>
Assign an id to your <input>. Add an event listener to it, like :
function getKeyCode() {
var key = window.event ? event.keyCode : event.which;
if(event.keyCode == 8 || event.keyCode == 46
|| event.keyCode == 37 || event.keyCode == 39) {
console.log(true);
//return true;
} else if (key < 48 || key > 57) {
console.log(false);
// return false;
} else {
console.log(true);
// return true;
}
}
var el = document.getElementById("myInput");
el.addEventListener("keypress", getKeyCode);
<input type="text" id="myInput">

Strange .replace() behaviour in Chrome browser

<div>
<input type="text" class="allownumericwithdecimal"/>saadad
</div>
$(".allownumericwithdecimal").live("keypress keyup ", function (event) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
var text = $(this).val();
if (!((event.which >= 48 && event.which <= 57) || event.which == 8 || event.which == 46 || event.which == 110 || event.which == 0)) {
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.'), text.indexOf('.').length).length > 2)) {
//event.preventDefault();
}
}
var text = $(this).val();
if ((event.which >= 48 && event.which <= 57) && (text.indexOf('.') != -1)) {
if ((text.substring(text.indexOf('.'), text.indexOf('.').length).length) > 2) {
//event.preventDefault();
}
if (event.which == 190) {
//event.preventDefault();
}
}
if (text.indexOf('.') != -1 && event.which == 190) {
if (text.match("^[0-9]+(\.[0-9]{0,2})?$")) {} else {
$(this).val('');
}
}
if (text.indexOf('.') == -1 && text.length > 7 && (event.which != 190 && event.which != 8 && event.which != 46 && event.which != 110 && event.which != 0)) {
event.preventDefault();
}
});
http://jsfiddle.net/Lx9h2smh/
The problem is If I type a value in textBox say 3434 and now I want to make it 35434 by putting cursor after 3 and pressing 5, it works fine in Firefox and IE but in chrome the 5 get added after value and it becomes 34345.
The culprit line is one which replace non numeric characters.
How to handle this issue??
Try this code, it runs. jsFiddle
I just do a test
if ( /[^0-9\.]/g.test($(this).val()) ) {
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
}
Explain
You just make sure that the user enter the value of what you want. You replace if the entered value is not an integer. Your regex mean: "Those which are not integer or dot (.), replace them with an empty value". That why You need to make this test. Therefore, if the user enters the value you want, it doesn't do the action replace and it doesn't pass to the test.
$(".allownumericwithdecimal").live("keypress keyup ",function (event) {
var caretP= $(this).getCursorPosition();
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
var text = $(this).val();
if (!((event.which >= 48 && event.which <= 57) || event.which ==8 || event.which ==46 || event.which ==110 || event.which ==0) )
{
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.'), text.indexOf('.').length).length > 2)) {
//event.preventDefault();
}
}
var text = $(this).val();
if((event.which >= 48 && event.which <= 57) && (text.indexOf('.') != -1))
{
if((text.substring(text.indexOf('.'), text.indexOf('.').length).length)>2)
{
//event.preventDefault();
}
if(event.which==190)
{
//event.preventDefault();
}
}
if(text.indexOf('.') != -1 && event.which==190 )
{
if(text.match("^[0-9]+(\.[0-9]{0,2})?$")){
}
else{
$(this).val('') ;
}
}
if(text.indexOf('.') == -1 && text.length>7 && (event.which!=190 && event.which !=8 && event.which !=46 && event.which !=110 && event.which !=0)){
event.preventDefault();
}
$(this).selectRange(caretP,caretP);
});
(function($) {
$.fn.selectRange = function(start, end) {
return this.each(function() {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if (document.selection) {
// IE
input.focus();
}
return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
}
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div>
<input type="text" class="allownumericwithdecimal"/>saadad
</div>
kepress seems to be the culprit when I changed the fiddle to just use keyup the replacement happened correctly (though the cursor shifted to the end)
http://jsfiddle.net/Lx9h2smh/1/
Just remove the 'keypress' event keypress event is very similar to the keydown event. If you press a button keypress event cannot identify the character. In your code it takes as current input Empty so it replace the character.

jquery keydown for only digits

i have an input box that is for payments, and i want to only allow number like x.xx, of course xxxx.x will work or xxxxx
i have the setup pretty much working minus some weird behavior. if the numbers 1 and 2 after the decimal can be 2 digits long (works) but if i press 3-9 then it only allows one of that digit. also 0's to the right of the decimal are being allowed infinitely.
heres what im working with. also i want to only allow the enter button and when its pressed then run a function
$('#money-button-input-box').keydown(function(event) {
var str = $(this).val()
if(str.length >= 1){
var rightHalf = str.split('.')[1];
if(rightHalf >= 3 && event.keyCode != 8 ){
event.preventDefault();
}
}
if( (event.keyCode == 190 || event.keyCode == 110) && str.replace(/[^.]/g, "").length >= 1 ){
event.preventDefault();
}
allowOnlyNumbers(event);
if (event.keyCode == 13) {
if($(this).val() == '')return;
enterPayment($(this));
}
});
and the function
function allowOnlyNumbers(events){
// Allow: backspace, delete, tab, escape, and enter
if ( events.keyCode == 46 || events.keyCode == 8 || events.keyCode == 9 || events.keyCode == 27 || events.keyCode == 13 ||
// allow decimals
events.keyCode == 190 || events.keyCode == 110 ||
// Allow: Ctrl+A
(events.keyCode == 65 && events.ctrlKey === true) ||
// Allow: home, end, left, right
(events.keyCode >= 35 && events.keyCode <= 39)) {
// let it happen, don't do anything
return;
} else {
// Ensure that it is a number and stop the keypress
if (events.shiftKey || (events.keyCode < 48 || events.keyCode > 57) && (events.keyCode < 96 || events.keyCode > 105 )) {
events.preventDefault();
}
}
}
http://jsfiddle.net/Qxtnd/
The problem of decimals is because you are using
rightHalf >= 3
which evaluates the actual number & not it's length, because javascript type-casts it to a number for the comparison. What you want instead is the number of digits, try
rightHalf.toString().length >= 2
Fiddle here http://jsfiddle.net/Qxtnd/1/
Edit
As long as rightHalf is a string you can do:
rightHalf.length >= 2
if rightHalf was a number you would get an exception doing that.
function isNumberKeyUp(event, obj, beforeLength, afterLength) {
var text = document.getElementById(obj).value;
var splitText = text.split('.');
if (splitText.length > 1 && splitText[1].length > afterLength) {
document.getElementById(obj).value = splitText[0] + "." + splitText[1].substring(0,2);
return false;
}
return true;
}
function isNumberKey(event, obj,beforeLength,afterLength) {
var keyCode1 = event.keyCode;
var keyCode = 0;
if (keyCode1 == 0)
keyCode = event.which;
else {
keyCode = keyCode1;
}
if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46 || keyCode == 13 || keyCode == 27 || keyCode == 127 ) {
var text = document.getElementById(obj).value;
if (keyCode == 46 && keyCode1 == 0) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
if (keyCode == 46) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
var splitText = text.split('.');
if (splitText[0].length >= beforeLength) {
if (keyCode == 46 && text.toString().indexOf(".") == -1) {
return true;
} else if (text.toString().indexOf(".") != -1)
{
return true;
}
return false;
}
}
else {
return GetDefault(event);
}
return true;
}
function GetDefault(event) {
var keyCode = event.keyCode;
if (keyCode == 0)
keyCode = event.which;
if (keyCode == 8 || keyCode == 9 || keyCode == 35 || keyCode == 36 || keyCode == 37 || keyCode == 38 || keyCode == 39 || keyCode == 40 || keyCode == 46 || keyCode == 118) {
return true;
}
return false;
}
Below is the html to call this events
<input type="text" onkeyup="return isNumberKeyUp(event,'txtID',9,2);" onkeypress="return isNumberKey(event,'txtID',9,2);" required="required" id="txtID" maxlength="12" value="1.00" name="txtID">
Here's the FIDDLE
rightHalf.length >= 2
$('#money-button-input-box').keyup(function () {
$(this).val(FormatNumber($(this).val()));
});
function FormatNumber(val){
var split = val.split('.');
if (split.length>1) return OnlyNumbersAllowed(split[0])+'.'+OnlyNumbersAllowed(split[1]);
else return OnlyNumbersAllowed(split[0]);
}
function OnlyNumbersAllowed(val){
return val.replace(/\D/g, '');
}
http://jsfiddle.net/Qxtnd/7/
You could easly put this regex in any function, instead of writing what you have now.

How the DEL Key with Mozilla Firefox

I need the help for my problem in my asp.net MVC3 application I have a textbox which is validating for currency format ($228.00) but in this text box it doesn't work for the DEL key because . and delete key have same ASCII key which 46. I also set a validation in this textbox for . is only one time will be accept in the text box so if "." entered one time then delete will not work.
Here is my validate Javascript:
function validateForCharacter(val, id, e) {
window.event.keyCode : -1;
var key = e.keyCode || e.charCode || e.which;
var currentChar = String.fromCharCode(key);
if (val.indexOf(currentChar) != -1 && currentChar == ".")
{
return false;
}
if (key >= 48 && key <= 57 || key == 46 || e.keyCode === 8 || e.keyCode === 9 || e.keyCode === 37 || e.keyCode === 35 || e.keyCode === 39)
{
$(this).val("");
return true;
}
return false;
}
This is my View (Html) code for textbox:
<input type="text" id="t1" onkeypress="return validateForCharacter(value, id, event)/>
Jquery does it right... but in case you need specifically detect delete key on Firefox or IE9 you can use event.key property.
I.E:
if (event.key == "Delete")
Live Demo:
$(document).ready(function() {
$("#nondeletable").on("keydown", function(event) {
$("#result").html(event.type + ": " + event.which);
if (event.key == "Delete")
$("#result").append(" <b>Delete!</b>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="nondeletable" />
<div id="result"></div>

javascript : key validation

im using javascript to validate keys in textbox. it is not working :(
function numeric(e) {
return ((e.keyCode == 8) ||
(e.keyCode == 9) ||
(e.keyCode > 47 && e.keyCode < 58) ||
(e.keyCode > 36 && e.keyCode < 41) ||
(e.keyCode == 46) ||
(e.keyCode > 95 && e.keyCode < 106) ||
e.keyCode == 190 ||
e.keyCode == 110);
}
help me...
function numeric(e) {
e = e || window.event;
keycode = e.keyCode || e.which;
if(keycode === 13){
alert("cheese");
}
}
I know that in I.E. you can set event.keyCode=0 to suppress the key appearing in the control. But I think you need to trap the onkeydown. Firefox might have an equivalent. This is good because it prevents the key actually "arriving" at the control.
Also keep in mind that you might need to handle combinations of Shift + key and alt + key.
a good debug technique for this sort of thing is to say windows.status = event.keyCode,
and you can see what the keycode is as you type it...
Just try out the following code. I have checked F5 keycode, you can check as you want
function disableKey(event)
{
if (!event) event = window.event;
if (!event) return;
var keyCode = event.keyCode ? event.keyCode : event.charCode;
if (keyCode == 116) {
showMsg("This functionality is disabled.");
window.status = "F5 key detected! Attempting to disabling default response.";
window.setTimeout("window.status='';", 2000);
// Standard DOM (Mozilla):
if (event.preventDefault) event.preventDefault();
//IE (exclude Opera with !event.preventDefault):
if (document.all && event && !event.preventDefault) {
event.cancelBubble = true;
event.returnValue = false;
event.keyCode = 0;
}
return false;
}
}
function setEventListenerForFrame(eventListener)
{
document.getElementById('your_textbox').onkeydown = eventListener;
//frames['frame'].document.onkeypress = eventListener;
}
<body onload="setEventListener(disableKey);">
Try this if you want a numbers only textbox:
function numbercheck(event) {
var unicode = event.charCode; var unicode1 = event.keyCode; if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1) {
if (unicode1 != 8) {
if ((unicode >= 48 && unicode <= 57) || unicode1 == 37 || unicode1 == 39 || unicode1 == 35 || unicode1 == 36 || unicode1 == 9 || unicode1 == 46)
{ return true; }
else
{ return false; }
}
}
if (navigator.userAgent.indexOf("MSIE") != -1 || navigator.userAgent.indexOf("Opera") == -1) {
if (unicode1 != 8) {
if (unicode1 >= 48 && unicode1 <= 57)
{ return true; }
else
{ return false; }
}
}
}
And in your textbox call it on the onkeypress event:
onkeypress="return numbercheck(event)"

Categories

Resources