How to add user input at caret position? - javascript

I am facing a weird issue regarding a textbox after using validation for preventing special characters.Lets say I enter some text in it.Now if I change the caret position in between the already entered text and try to add text there, the caret automatically jumps to the end of the text.
Any workaround for this?
Note:- I am using IE 11.
Textbox :-
<div class="form-group">
<label data-i18n="rpt_name"></label>
<span class="required">*</span>
<input type="text" class="form-control" id="subNameID">
</div>
The source of error is validation for avoiding special characters.
$('#subNameID').bind('keypress', function (e) {
if ($('#subNameID').val().length == 0) {
var k = e.which;
var ok = k >= 65 && k <= 90 || // A-Z
k >= 97 && k <= 122 || // a-z
k >= 48 && k <= 57; // 0-9
if (!ok) {
e.preventDefault();
}
}
})
Also tried using below solution but gives the same issue.
$("#subNameID").on("keypress keyup paste", function (e) {
if (e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 8)
return true;
this.value = this.value.replace(/[^a-zA-Z0-9\-\._\s]/g, '');
});

Related

How to restrict apart from alphabets and numbers any other keys (function keys, shortcut keys etc.) press action on datatable search input?

Jquery:
Is there please an option to start the search only alphabet and number keys have been typed in?
Datatable globally searching should initiate at least with 3 characters
$(document).on('draw.dt','.dataTable', function() {
$(".dataTables_filter input").off().on("input keyup", function(e) {
// if value length is greater than 3 or user press enter (keycode = 13) on search we will search on datatable
if(this.value.length >= 3 || e.keyCode == 13 || this.value == "") {
var dataTable = $('.table').DataTable();
dataTable.search(this.value).draw();
}
});
});
Solution:
Check this solution. I hope, it will work.
$(document).on('draw.dt','.dataTable', function() {
$(".dataTables_filter input").off().on("input keyup", function(e) {
// if value length is greater than 3 or user presses enter (keycode = 13) on search
// we will search on datatable
if(this.value.length >= 3 || e.keyCode == 13 || this.value == "") {
var checkBackspaceEnter = e.keyCode == 8 || e.keyCode == 13;
// if user removes a character from search we will search
var checkAlphabet = (e.keyCode >= 58 && e.keyCode <= 90);
// check on alphabets
var checkNum = (e.keyCode >= 48 && e.keyCode <= 57
|| e.keyCode >= 96 && e.keyCode <= 105);
// check on number values
var ctrlCombine = (e.keyCode == 17 || ((e.keyCode == 65 || e.keyCode == 67 )
&& e.ctrlKey));
// don't search when user hits Ctrl+A or Ctrl+C
checkAlphabet = ((ctrlCombine == false) ? checkAlphabet : false);
if (checkAlphabet || checkNum || checkBackspaceEnter) {
var dataTable = $('.table').DataTable();
dataTable.search(this.value).draw();
}
}
});
});
Use regular expressions with preg_replace to remove letters other than alpha-numeric on every keyup and then check the length of a string.
Hope you get the desired result.

How to valid Numeric values onkeypress

I have this simple HTML document
<input type="text" id="my_text" onkeypress="valid_numbers(event);" size="30"/>
<script type="javascript">
function valid_numbers(e)
{
var key=e.which || e.KeyCode;
if ( key >=48 && key <= 57)
// to check whether pressed key is number or not
return true;
else return false;
}
</script>
What I want is:
onkeypress of my_text if the pressed key is number allow otherwise deny writing of the character.
But the above code doesn't work, my_text element accept any character, what is wrong with the above code ?!..
Help Please!..
I think the easy way to do this would be:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' />
But the problem comes up when you paste some text then HTML5's number type input may be a better choice:
<input type="number" />
BTW you can find better suggestions if you search the SO like this.
Some very complex answers, but it can be as simple as using a regular expression to return the result of checking if the input was a number or not:
<input onkeypress="return /\d/.test(String.fromCharCode(event.keyCode || event.which))">
Note that this will not stop entering of non-digit characters by pasting, dragging and dropping or script.
var input = document.getElementById('my_text');
input.onkeydown = function(e) {
var k = e.which;
if ( (k < 48 || k > 57) && (k < 96 || k > 105) && k!=8) {
e.preventDefault();
return false;
}
};
and
<input type="text" id="my_text" size="30"/>
Allows only [0-9] number, numpad number, arrow, BackSpace, Tab, Del as wel as Ctrl + C, Ctrl + V, Ctrl + A.
Allow only one dot.
Remove if last char is dot on a blur event.
element.on('keydown', function(e) {
var arrowsKeyCodes = [37, 38, 39, 40];
var numPadNumberKeyCodes = [96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
var dots = [110, 190];
var tabBackDel = [8, 9, 46];
var acv = [65, 67, 86];
// Allow only one dot.
if (e.target.value.indexOf('.') !== -1 && dots.indexOf(e.keyCode) !== -1) {
event.preventDefault();
}
// allow only [0-9] number, numpad number, arrow, BackSpace, Tab, Del
// Ctrl + C, Ctrl + V, Ctrl + A
if (
(e.keyCode < 48 &&
arrowsKeyCodes.indexOf(e.keyCode) === -1 || e.keyCode > 57 &&
numPadNumberKeyCodes.indexOf(e.keyCode) === -1 &&
dots.indexOf(e.keyCode) === -1
) &&
tabBackDel.indexOf(e.keyCode) === -1 &&
(e.ctrlKey === false || e.ctrlKey === true && acv.indexOf(e.keyCode) === -1)
) {
e.preventDefault();
}
});
element.on('blur', function(e) {
var value = e.target.value;
if (value.substring(value.length - 1) === '.')
e.target.value = value.substring(0, value.length - 1)
});
Have not tried this out, but you can use parseInt in your function to check like:
var t = document.getElementById("my_test").value;
if (parseInt(t) == 'NaN') {
// not a number
}
<html>
<body>
<input id="edValue" type="text" onKeyPress="edValueKeyPress()" onKeyUp="edValueKeyPress()"><br>
</body>
<script>
function edValueKeyPress()
{
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
if ( s >=48 && s <= 57)
// to check whether pressed key is number or not
return true;
else return false;
}
</script>
</html>
Use this tested code.it's help you.
You can Simply use JavaScript or HTML5 to execute this
JavaScript:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
HTML 5 (does not require JavaScript, and also does not behave in standard way in many modern browsers.)
<input type="number">
FIDDLE
More on this may look here.

jquery - Numeric Only Text Field

I found this very short clean code to only allow numeric chars in a text field. Currently it only covers numbers 0-9 and backspace and delete. I wanted it to also include decimal/period, so I have been fighting with this to simply include keycode 110 and/or 190. I can not get it to work. Can anyone see what I am doing wrong?
$(document).ready(function() {
$('input.numberinput').bind('keypress', function(e) {
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) ) || (e.which!=110) ? false : true ;
});
});
jsfiddle here: http://jsfiddle.net/justmelat/EN8pT/
html
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber1" id="txtNumber1" value="" class="numberinput" />
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber2" id="txtNumber2" value="" class="numberinput" />
</div>
Try:
$(document).ready(function () {
$('input.numberinput').bind('keypress', function (e) {
return !(e.which != 8 && e.which != 0 &&
(e.which < 48 || e.which > 57) && e.which != 46);
});
});​
JsFiddle: http://jsfiddle.net/EN8pT/1/
With the above answer you can still do 0.23.12.33 which is not a valid number.
http://www.texotela.co.uk/code/jquery/numeric/ is a great little lightweight plugin that I have used a lot. It takes the pain out of the above.
$("#input").keydown(function(event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
// Allow: backspace, delete, tab, escape, and enter
if ( key == 46 || key == 8 || key == 9 || key == 27 || key == 13 || key == 110 || key == 190 ||
// Allow: Ctrl+A
(key == 65 && theEvent.ctrlKey === true) ||
// Allow: home, end, left, right
(key >= 35 && key <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (theEvent.shiftKey || (key < 48 || key > 57) && (key < 96 || key > 105 )) {
theEvent.preventDefault();
}
}
});
with keycode 110 and 190

Capturing the tab key using JavaScript in Firefox

I use the following to restricts user to enter only some characters.
When I press tab, the cursor does not point to next control (in Mozilla). But it works fine in IE.
// Restricts user to enter characters other than a to z, A to Z and white space( )
// Rauf K. 06.11.2010
$("input:text.characters_only").keypress(function(e) {
if (!((e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) || e.which == 32 || e.which == 8 || e.which == 9)) {
return false;
}
});
I would recommend trying e.keyCode instead of e.which. Here is a SO link that describes a good method of getting the key strike into a single variable regardless: jQuery Event Keypress: Which key was pressed?
Perhaps if you start with something like:
if (e.keyCode === 9) { // TAB
return true;
}

Detect numbers or letters with jQuery/JavaScript?

I want to use an if-statement to run code only if the user types in a letter or a number.
I could use
if (event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || ...) {
// run code
}
Is there an easier way to do this? Maybe some keycodes don't work in all web browsers?
If you want to check a range of letters you can use greater than and less than:
if (event.keyCode >= 48 && event.keyCode <= 57) {
alert('input was 0-9');
}
if (event.keyCode >= 65 && event.keyCode <= 90) {
alert('input was a-z');
}
For a more dynamic check, use a regular expression:
const input = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9-_ ]/.test(input)) {
alert('input was a letter, number, hyphen, underscore or space');
}
See the MDC documentation for the keyCode property, which explains the difference between that and the which property and which events they apply to.
Use event.key and modern JS!
No number codes anymore. You can check key directly.
const key = event.key.toLowerCase();
if (key.length !== 1) {
return;
}
const isLetter = (key >= 'a' && key <= 'z');
const isNumber = (key >= '0' && key <= '9');
if (isLetter || isNumber) {
// Do something
}
You could also use a simple regex. ^$ ensures 1 char, i ignores case
/^[a-z0-9]$/i.test(event.key)
or individually:
const isLetter = /^[a-z]$/i.test(event.key)
const isNumber = /^[0-9]$/i.test(event.key)
First, if you're doing this, make sure it's in the keypress event, which is the only event for which you can reliably obtain information about the character the user has typed. Then I'd use the approach Andy E suggested:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
alert("Letter or number typed");
}
};
If you want to check for backspace, I'd use the keydown event instead and check for a keyCode of 8 because several browsers (including Chrome) do not fire a keypress event for the backspace key.
if (event.keyCode >= 48 && event.keyCode <= 90) {
// the key pressed was alphanumeric
}
For numeric values:
function validNumeric() {
var charCode = event.which ? event.which : event.keyCode;
var isNumber = charCode >= 48 && charCode <= 57;
if (isNumber) {
return true;
} else {
return false;
}
}
Here, 48 to 57 is the range of numeric values.
For alphabetic values:
function validAlphabetic() {
var charCode = event.which ? event.which : event.keyCode;
var isCapitalAlphabet = charCode >= 65 && charCode <= 90;
var isSmallAlphabet = charCode >= 97 && charCode <= 122;
if (isCapitalAlphabet || isSmallAlphabet) {
return true;
} else {
return false;
}
}
Here, 65 to 90 is the range for capital alphabets (A-Z), and
97 to 122 is the range for small alphabets (a-z).
As #Gibolt said, you should use event.key.
Because charCode, keyCode and which are being deprecated.
To detect letters & numbers when using <input> or <textarea> you can use input event.
This event fires when <input> or <textarea> value changes so there is no need to worry about keys like Alt, Shift, arrows etc. Even more - if you use mouse to cut part of the text the event fires as well.
var element = document.getElementById('search');
element.addEventListener('input',function(e){
console.log(element.value);
});
<input id="search" type="text" placeholder="Search" autocomplete="off">
Simply you can add your Html forms in the input field like this:
...onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"
You don't need any function. This Validation works only with the email field. Don't use naming or number. To use number, remove email regular expression like this:
...onkeypress ="return /[a-z ]/i.test(event.key)" required accesskey="4"
For number only:
...onkeypress ="return /[0-9]/i.test(event.key)" required accesskey="4"
Don't forget, to add for each input fields their own value.
<div class="form-group">
<input type="Email" class="form-control " id="EMAILADDRESS" name="EMAILADDRESS" placeholder="Email Address" autocomplete="false" onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"/>
</div>
$('#phone').on('keydown', function(e) {
let key = e.charCode || e.keyCode || 0;
// 32 = space - border of visible and non visible characters - allows us to backspace and use arrows etc
// 127 - delete
if (key > 32 && (key < 48 || key > 58) && key !== 127) {
e.preventDefault();
return false;
}
});
modified answer of #user4584103, allows us to remove characters, and navigate in input box and filter out every not number character
You can also use charCode with onKeyPress event:
if (event.charCode > 57 || event.charCode < 48) {
itsNotANumber();
} else {
itsANumber();
}
number validation, works fine for me
$(document).ready(function () {
$('.TxtPhone').keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
// only numbers
if (key < 48 || key > 58) {
return false;
}
});
});
Accept numbers or letters with JavaScript by Dynamic Process using regular expression.
Add onkeypress event for specific control
onkeypress="javascript:return isNumber(event)"
function numOnly(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
function Alphanum(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
Use $.isNumeric(value); return type is boolean
$(document).ready(function () {
return $.isNumeric(event.keyCode);
});
A very simple, but useful method to try (i needed on a keyup event, letters only),
use console.log() to check, typeOfKey is a string so you can compare. typeOfKey is either (Digit or Key)
let typeOfKey = e.code.slice(0,-1)
if(typeOfKey === 'Key'){
console.log(typeOfKey)
}

Categories

Resources