How to allow only numbers in a textarea using jQuery? - javascript

I've seen a similar question on SO but my approach is slightly different. I have a textarea that I want to accept only numbers as an input. Currently all inputs are allowed and the error alert isn't triggered.
I think the problem may be that the key being pressed isn't being passed into my validate function, but I'm not sure how to do that without using the html onkeypress which I'm trying to avoid using.
HTML:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
JS:
$(document).ready(function () {
var noteNumberInput = document.getElementById("noteNumberInput");
//VALIDATE NOTE NUMBER TEXTAREA
function validate() {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if (keycode < 48 || keycode > 57) {
alert("Please only enter the note number e.g. '1', '2' etc.")
return false;
}
}
noteNumberInput.addEventListener("keypress", validate);
});

Your function needs the key parameter:
function validate(key) {
....

Related

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">

changing character code with js and show the new character instead

I want to write a code that if a user press a key, It changes the keyCode or charCode of the User event and trigger the event with a new charcode,
I wrote this code in jsfiddle but this code doesn't work because of too much recursion.
function convert(e, elem) {
function getKey(event) {
if (event.which == null) {
return event.keyCode // IE
} else if (event.which != 0 && event.charCode != 0) {
return event.which // the rest
} else {
return null // special key
}
}
var key = getKey(e);
key++;
return key;
}
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
$(this).trigger(e);
});
<input type="text" class="myInput" />
any Idea that help my code work would be appreciated.
Thanks alot.
Regarding the recursion issue, you need to add a stopping condition, for example:
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
if(!e.isSecondTrigger){
e.isSecondTrigger = true;
$(this).trigger(e);
}});
This way, you only change the value once. However, as was stated by LShetty in the comments section, the event values are read only - you can't change the value of the button that was already pressed and in that way change the input text. In order to do this, you need to manually change the value of the input text after each user action (i.e. hold the value of the input text at each key press, modify it when the user presses a key, and then overwrite the input field value with the output).

jquery restrict only < and > symbol in textbox

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"/>

Javascript validation C#.NET

I am having a problem validating a textbox to not allow spacing. When the user enters a space I would like it to display an alert message and then clear the textbox, but the textbox doesn't clear. This is what I have so far.
function ValidateSpace () {
var SerNum = document.getElementById("txtbox1")
if (event.keyCode == 32) {
alert("This field may contain no spaces.");
document.getElementById ("txtbox1").value=""
}
}
I have users trying to put multiple entries in this space but it should only accept one. The textbox is for inventory purposes so it would change the nature of the data if I were to remove spaces
I suppose that you have to bind keyDown event on textbox
try this jquery code to remove live the spaces
$("#IdOfTheTextBox").on("keydown", function (e) {
return e.which !== 32;
});​​​​​
If you can't use jquery try with this javascript function (onkeypress event of textbox)
function NoSpace() {
if (event.keyCode == 32) {
event.returnValue = false;
return false;
}
}
if you want to remove spaces after the input you can do this
var noSpaces = document.getElementById("txtbox1").value.replace(/\s/g, "");

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

Categories