jquery restrict only < and > symbol in textbox - javascript

Code:
$j("#<%= txtGradingScale.ClientID%>").bind("keypress", function (e)
{
var keyed = $j(this).val();
$j("#<%= txtGradingScale.ClientID%>").html
(keyed.replace(/\<>/gi, ''));
});
Have to restrict greter than and lesser than symbol in textbox while entering .
above code is not working pls suggest the method .i tried keyCode and Charcode but it's not working

The reason it's not working is because the regular expression /\<>/ (the escape character \ is not needed) is looking for <> and not the characters by themselves, what you want to do is:
$('textarea[name="test"]').keyup(function(e) {
$(this).val($(this).val().replace(/[<>]/ig, ''));
});
This will match any instance of the < and > characters no matter what order they appear in.
You should also use keyup instead of keypress because keypress will only trigger after the next key gets hit, while keyup will trigger whenever the key is released.
Fiddle

You want to test using e.which and compare with corresponding codes for < and >. If you return false or invoke e.preventDefault() when they are encountered, that should do it.
$('#myText').on('keypress', function(e) {
if( e.which === 60 || e.which === 62 ) {
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="myText" id="myText"/>

Related

jQuery to prevent user from inputting if regular expression is not matched by using preventdefault

Every time user enter, value is checked with regular expression, I'm trying to restrict user from entering further into input field if regexp is not matched
Using keyup event, preventdefault never fires and using keypress event, user is unable to input at all because in the begining, value in input field shows as "" (nothing)
var discountRegex = /(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/
$("#" + (idOfElement)).on("keyup",function (e) {
var val=this.value
var k = e.keyCode
if(k==46 ||(k > 48 && k <97)){
console.log(k)
return discountRegex.test(val);
}
});
in the above code idOfElement is the id i get on whichever field i focus.
Please refer sample code. If input key is invalid input will not accept it. Also please find fiddle for same in comment.
<input type="text">
$(document).ready(function(){
$("input").bind('keypress', function(e) {
var str = e.keyCode;
if (/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/.test(str)) {
alert('Invalid')
e.preventDefault();
} else {
alert('Valid');
}
});
});
You can check if the regex is matched and if not you can remove the last char like the example below
I updated the code with keydown example
Example

Real time input text filtration which allows only numbers

Hello I'm trying to make real time input type="text" filter which allows only numbers and dot, using javascript.
I wrote
Javascript:
<script>
function thirdTaskFunction(evnt) {
evnt = evnt || window.event;
var charCode = evnt.which ? evnt.which : evnt.keyCode;
return /\d/.test(String.fromCharCode(charCode));
}
function thirdTaskFunction(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if(charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function thirdTaskFunction() {
var thirdInput = document.getElementById("thirdTaskInputText");
thirdInput = thirdInput.onchange = thirdTaskFuncion;
var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
if(!valid.test(this.value)) {
var compare = this.value.match(number);
this.value = compare ? compare[0] : '';
}
}
</script>
HTML:
<div id="thirdTaskDIV">
<input id="thirdTaskInputText" type="text" placeholder="Type a number" autofocus onkeypressed="return thirdTaskFunction(event);">
</div>
I was trying many ways, every thirdTaskFunction() method wasn't work, I was tested solution on w3schools so maybe this is reason? But I think that I dont remember about something that make it works. And I know is very similar to "HTML text input allow only numeric input" but it didnt works.. So I hope somebody show me whats pappyn here.
One way to allow only numbers in an input field is using a keypress event listener. So you'll want to select the input field and give it an event listener, like this:
const inputField = document.querySelector("/*input field id here*/");
inputField.addEventListener("keypress", function(e){
if(e.keyCode > 48 && e.keyCode < 57){
e.preventDefault();
}
}
This function checks if the key that's pressed matches a number key, and if it doesn't, prevents the default action which in this case is printing the character to the input field.
If you have any questions, I'll do my best to answer them!
P.S. The keyCode numbers used are estimates based on memory, to get the key codes simply do a quick search on google for "ASCII key codes".
The event code (NOT keyCode since the keyCode property is deprecated) for the dot is Period and the event code for the numbers 0 to 9 comes in the form Digit0, Digit1 and so on.
Just use the keydown event listener to retrieve the event code and then use the includes() method to check if the current key has a code that includes "Digit" or "Period" and restrict input of that character if it doesn't include either of those two by using preventDefault() like this:
const input = document.getElementById('thirdTaskInputText');
function checkKey(e) {
if(e.code.includes("Digit") || e.code.includes("Period")) {
console.log("valid input");
} else {
e.preventDefault();
console.log("not a number!");
}
}
input.addEventListener('keydown', checkKey)
<input id="thirdTaskInputText" type="text" placeholder="Type a number">
Without the console logs, you can further simplify the above code to a single if statement using the bang operator ! like this:
const input = document.getElementById('thirdTaskInputText');
function checkKey(e) {
if(!(e.code.includes("Digit") || e.code.includes("Period"))) e.preventDefault();
}
input.addEventListener('keydown', checkKey)
<input id="thirdTaskInputText" type="text" placeholder="Type a number">

Allow only numbers in Input field IOS

Ok Well. I want to restrict input field to accept only numbers with maxlength 5 characters.
My Try:
HTML
<input type="number" maxlength="5" onKeyDown="numbersOnly(event);/>
<input type="text" pattern= "[0-9]" onKeyDown="numbersOnly(event);/>
Javascript
function numbersOnly(event,length)
{
return event.ctrlKey || event.altKey
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46)
|| (event.keyCode>47)&&(event.keyCode<=57) ;
}
All works in firefox. But when i check with safari ipad, it accepts special characters like ()#!#$&. I used alert function for debugging. It returns same keyCode for # and 2 , 3 and # and so on. I tried keyUp,keyPress events and event.charCode,event.which,event.key. Nothing works
So how to differentiate it and i need support for backspace , enter , delete, arrow keys also.
I've made this once and haven't been able to break it. Tested on iPad.
// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
this.value = this.value.replace(/[^0-9]+/g, '');
if (this.value < 1) this.value = 0;
});
// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});
This also accounts for copy/paste and drag and drop text, which people often forget. You can add the max-length to the onchange.
Using type="number" on an input prevents you from reading non-numerical input values via input.value (it will then return an empty string) and thus eliminates the possibility of filtering invalid user input (+-.e) while keeping the valid numbers. Thus you have to use type="text". Example:
$('.input-number').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="input-number" type="text" maxlength="5">
If you want the text-cursor not to move when pasting or typing invalid input, have a look at my answer to a similar question here: HTML input that takes only numbers and the + symbol
Be careful the iOS keyCodes are not the same desktop computers. See IOS keyCodes in Javascript
<input type="number" maxlength="5" onkeypress="numbersOnly(event);/>
var numbersOnly = function(event) {
if(event.keyCode >= 48 && event.keyCode <= 57) {
return false;
} else {
event.preventDefault();
}
}
If you want to enter the only numbers in input type number fields. this will be helpful, It will work on iPhone and iPad as well.
$(document).on('keypress', 'input[type="number"]', function (event) {
return event.code.includes('Digit') || event.code.includes('Numpad') || event.code.includes('Period');;
});

How to use Javascript to filter and ignore keypresses on an input field?

I need to stop accepting input (keystrokes) on an HTML form input field when the length limit has been reached. In straight-up HTML I can do this with maxlength="3" or whatever the length is, but I would like to handle it through Javascript if possible so I can do it together with the next requirement.
I also need to filter the input so that if a field is numeric only numbers can be typed, and if there's a mask or regex any inputs conform to the mask/regex.
Is there a "standard" way to do this in, Javascript, particularly in Dojo 1.9? (I know everybody uses JQuery but we use Dojo because.)
For dojo, if you need any sort of validation, I would use the ValidationTextBox, which takes "maxLength" as a property AND allows for all sorts of nifty validation schemes. The reference for ValidationTextBox is here:
http://dojotoolkit.org/reference-guide/1.9/dijit/form/ValidationTextBox.html
I used pure Javascript because I am not familiar with Dojo, but these event listeners can probably be cleaned up with Dojo.
var input = document.getElementsByTagName('input')[0],
error = document.getElementById('error');
input.addEventListener('keypress', function(e) {
if(e.which < 48 || e.which > 57) {
e.preventDefault();
error.innerHTML = 'Must be a digit';
} else if(e.target.value.length >= 3) {
e.preventDefault();
error.innerHTML = 'Cannot be more than 3 digits';
} else {
error.innerHTML = '';
}
});
We listen to a keypress and then, to make sure it is a digit, we seek that the key pressed was between 48-57 (0-9). If not, then we prevent the key press and show an error. Then we check the input's current length. If it is too long, then prevent the key press and show an error. Otherwise, it worked and we allow the event and clear the error.
You maybe looking for this:
<input id="text" type="text"/>
$('#text').on('keypress',function(e){
var numero = this.value.length;
console.log(this.value.length);
if (e.which != 8 && e.which < 48 || e.which > 57)
{
return false
}
else if (numero === 3 && e.which != 8){
return false //alert user here
}else{
return true // allow backspace only (8)
}
}
);
DEMO

How to specify which characters are allowed in a textbox with jQuery?

http://jsfiddle.net/WhP8q/
I'm trying to restrict input to alpha numeric, 0-9, A-Z,a-z.
The ASCII table i'm referencing: http://www.asciitable.com/
Here is what I have so far
$(function() {
$("input").bind("keydown paste", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var c = code;
var letterAllowed = ((c > 47 && c < 58) || (c > 64 && c < 90) || (c > 96 && c < 123))
if (code > 32 && !letterAllowed) {
return false;
}
});
});​
right now, the tilde (~) character is prevented from getting input into the field, but other special / shift characters such as !##$% all get entered into the text field.
I'm pretty sure my logic is sound, but my issue is with some misunderstanding of javascript bindings? idk
Preventing character input for only some cases is very complicated in javascript, as in the keypress event (the one you'd want to prevent) you do not know the afterwards value of your input, but only the keycode of the pressed key (and not even the resulting char for sure). Also, you will need to care about special keys like or .
I'd recommend something like this:
$("input").on("keypress keyup paste", function(e) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
In case of restrict the character you enter, You can replace the character which is not alphanumberic.
<input type='text' id="txtAlphaNumeric"/>
<input type='text' id="txtNumeric"/>
<input type='text' id="txtAlphabet"/>
<script type="text/javascript">
$(function() {
$('#txtNumeric').keyup(function() {
if (this.value.match(/[^0-9]/g)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
$('#txtAlphabet').keyup(function() {
if (this.value.match(/[^a-zA-Z]/g)) {
this.value = this.value.replace(/[^a-zA-Z]/g, '');
}
});
$('#txtAlphaNumeric').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
});
});
</script>
Answer taken from: jquery allow only alphanumeric
Turns out, I need to do the following:
$("input").keypress(function(e){
var code = e.charCode;
charCode will give the actual character code of the typed letter, rather than the ascii code of the last pressed key
see http://api.jquery.com/keypress/

Categories