CLEditor - Lose focus if maxlength is reached - javascript

I'm trying to recreate a maxlength - function for CLEditor. The objective is:
If a text is entered into a textbox and its longer than the set maxlength, the textbox should lose its focus so that it's not possible, to write any further letters.
What I've achieved so far is that the CLEditor recognizes when the text gets longer than my maxlength.
For losing the focus I've tried a simple return (i.e. return; return false;) and some .blur()-methods (i.e. $(frameDesc).blur(); and cledDesc.$area.blur();).
But those are not working. I'm still able to fill in text even maxlength is reached.
Please have a look at the code:
$("#profileForm_description").cleditor({width: 430, height: 125});
var cledDesc = $("#profileForm_description").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
$(frameDesc).bind('keypress change', function(){
var text = textWithoutHTML(cledDesc.$area.val());
if(text.length >= 650){
console.log("Longer than MaxLength");
//lose focus
}else{
//Do something
}
});
Any help and hints would be appreciated :)

Solved this one. That was pretty tricky. The solution (for me) is:
Using the keydown instead of the keypress - event.
So if I'm trying to put in some text in my textbox and maxlength is reached, I'm not able to go on writing. But to be able to delete some text, I need to except the Backspace-key from being rejected too. So I've put in a check, if the pressed key is the backspace-key.
This is what the code looks like now:
$("#profileForm_description").cleditor({width: 430, height: 125});
var cledDesc = $("#profileForm_description").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
$(frameDesc).bind('keydown change', function(event){
var text = textWithoutHTML(cledDesc.$area.val());
if(text.length >= 650 && event.which != 8){
console.log("Longer than MaxLength");
//lose focus / stop writing
return false;
}else{
//Do something
}
});

I've added some code to make it work.
I catch even the "canc" key (and others)
Before checking the length of the text I update the textarea, it looks like CLEditor has an internal cache and I had a strange behaviour after deleting and reentering text.
This is working perfectly for me:
var cledDesc = $("#oodsummary").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
var limit = 10;
$(frameDesc).bind('keydown', function(event){
cledDesc.updateTextArea();
var text = cledDesc.$area.val();
if(text.length >= limit &&
event.which != 8 && // back
event.which != 46 && // canc
event.which != 37 && // left
event.which != 38 && // up
event.which != 39 && // right
event.which != 16 && // shift
event.which != 20 && // caps lock
event.which != 91 && // os special
event.which != 18 // alt
) {
alert("Il testo inserito risulta essere troppo lungo.");
cledDesc.$area.val(text.substr(0, limit)).blur();
return false;
}else{
cledDesc.updateTextArea();
return true;
}
});

Related

Javascript Validation on Control-V for the Textbox

I have to validate the textbox to enter only alpha numeric characters.
The function validateAlphaNumeric(evt, txtbox) fires onkeypress event on textbox.
Below is the function written in Javascript.
But I am not able to get the value of the textbox if I do Ctrl+V. I need to validate if user pastes.
Can any one suggest me on this?
function validateAlphaNumeric(evt, textBox) {
/* File Description : Numbers,Characters,Hyphen(-),Slash(/)and Space */
var charCode;
charCode = (evt.which) ? evt.which : window.event.keyCode;
if (charCode >= 97 && charCode <= 122 || charCode >= 65 && charCode <= 90 || charCode == 8 || charCode >= 48 && charCode <= 57 || charCode == 45) {
return true;
}
else {
var errorMsg = document.getElementById(textBox.id + 'Error');
if (errorMsg != null) {
errorMsg.innerText = "Please Enter Alpha – Numeric Characters only";
}
return false;
}
}
I have found an answer:
Try this on onpaste event.
Surely will work out.
I tried this:
function onPaste(evt, textBox) {
pastedText = window.clipboardData.getData('Text');
if (pastedText matches regExp) {
return true;
} else {
//display error msg
return false;
}
}
Regards..
validate text box on onblur() event of that TextBox. your problem will sure get solved.
from html5 on there is the oninputevent which does exactly what you want.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.oninput
In the handler, check that the value property of the text box contains only allowed characters.
Note that IE9 has buggy support for this event - basically it doesn't recognize character deletion, but it doesn't affect you because you can't make the text invalid just by removing stuff. See here for more detail:
http://help.dottoro.com/ljhxklln.php
If you can't use oninput because you really need to support IE8-IE7 (hint: you don't really want to) you can instead fix your code by listening to the onpaste event too to get text paste events.

Selecting text on-the-fly from textbox leaves out last character in javascript

I'm trying to get the text from a textbox as a user types, so that I can parse it and display information accordingly as the user enters a command. However, it seems as though the function I'm writing is getting the text from the box before the letter is entered into the text box. How do I prevent the function from grabbing the content from the textbox before the typed character is entered? I considered grabbing the id of the key and altering the inputted string accordingly, but I feel like there should be a better way.
The code:
$('#inputConsoleForm').keydown(function(event){
//Get key code
var code = (event.keyCode ? event.keyCode : event.which);
//Get console text (doesn't behave as expected)
var consoleCommand = document.inputConsoleForm.console.value;
function parseConsoleCommand(consoleCommand) {
/* Returns true if command is valid*/
}
if(code === 13) {
event.preventDefault();
if(!parseConsoleCommand(consoleCommand))
alert("INVALID COMMAND LINE");
else
attemptExecute();//Runs the command
}
if(code === 32 || (code >= 48 && code <= 123) || code === 61 || code === 109 || code === 188 || code === 8) {
if(parseConsoleCommand(consoleCommand)){
$(document.inputConsoleForm.console).css("background-color", "#FFDFDF");
}
else{
$(document.inputConsoleForm.console).css("background-color", "");
}
}
});
You could use the HTML5 input event (falling back to the propertychange event in IE < 9). Here are two answers detailing how to do this:
jQuery keyboard events
Catch only keypresses that change input?
Use "change" for best results I'd say. You could continue to use keydown (or keyup) but you'll have to fetch the key being pressed from the event object and append it to the text string.

Which is the proper way of filtering numeric values for a text field?

I'm working on a textfield working with the kind of validation that wouldn't let you enter other than numeric values. As so, my initial code looked quite simple and similar to this:
$(textField).onKeyPress(function(e) {
if (e.which < 48 && e.which > 57)
e.preventDefault();
});
This is fairly strightforward, but turns that (in the latest version of all browsers) Firefox will make this also prevent movement with the arrow keys and delete/backspace keys, whereas the other browsers would not.
Looking around I found that I would need to also check for these keys, and check for different properties exposed in the e event reference.
My final code looks something like this:
$(textField).onKeyPress(function(e) {
var code = e.which || e.keyCode;
if (code > 31 // is not a control key
&& (code < 37 || code > 40) // is not an arrow key
&& (code < 48 || code > 57) // is not numeric
&& (code != 46) // is not the delete key
)
e.preventDefault();
});
However, this feels to be too much to solve a fairly simple problem as just preventing non-numeric.
What am I doing wrong? Which is the best practice in terms of this kind of validation?
We'll respond to both keypresses, and the blur event. When somebody press a key, we check to see if the key entered is a number. If it is, we permit it. Otherwise, we prevent it.
If the field is blurred, we remove any non-numerical values, and all those values that follow. This will prevent the user from pasting in non-numerical strings:
$("#textfield").on("keypress blur", function(e){
if ( e.type === "keypress" )
return !!String.fromCharCode(e.which).match(/^\d$/);
this.value = this.value.replace(/[^\d].+/, "");
});
Demo: http://jsfiddle.net/jonathansampson/S7VhV/5/
Working demo http://jsfiddle.net/Pb2eR/23/ Updated Copy/Paste demo: http://jsfiddle.net/Pb2eR/47/ (In this demo wit you copy paste string with characters it won't allow else it will allow number to be copy pasted: tested in safari)
Demo for arrow key to work http://jsfiddle.net/gpAUf/
This will help you.
Note: in this version even if you copy paste it will set it to empty input box, tested in safari lion osx :)
Good Link: [1] How to allow only numeric (0-9) in HTML inputbox using jQuery?
code
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
​
html
<input type="text" class="hulk" value="" />
​
Update for copy paste stuff
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
$(".hulk").bind('input propertychange', function() {
this.value = this.value.replace(/[^0-9\.]/g,'');
});​
code from another demo
$(".hulk").bind('input propertychange', function(event) {
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
this.value = this.value.replace(/[^0-9\.]/g,'');
});
​
this will allow both int.
it also removes text if user copy and paste with mouse.
$(document).ready(function () {
$('#textfield').bind('keyup blur', function (e) {
if (e.type == 'keyup') {
if (parseInt($(this).val()) != $(this).val()) {
$(this).val($(this).val().slice(0, $(this).val().length - 1));
}
} else if (e.type == 'blur') {
$(this).val('');
}
});
});

Remove Any Spaces While Typing into a Textbox on a Web Page Part II

This involves HTML + JS and/or JQuery:
I would have commented on the previous post, but I don't have comment reputation or cannot comment for some reason.
Josh Stodola's great code from Part I is as follows:
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
This works great except .replace puts the cursor at the end of the string on every keyup (at least in IE8 and Chrome).
As a result, it renders the left & right cursor keys useless, which is needed inside the input box.
Is there any way to enhance the above code so that the cursor keys do not activate it, but so that the text still gets updated on the fly?
The best solution is to avoid using key events to capture text input. They're not the best tool for the job. Instead, you should use the HTML5 oninput event (supported in the latest and recent versions of every current major browser) and fall back to onpropertychange for older versions of Internet Explorer:
var alreadyHandled;
txt.bind("input propertychange", function (evt) {
// return if the value hasn't changed or we've already handled oninput
if (evt.type == "propertychange" && (window.event.propertyName != "value"
|| alreadyHandled)) {
alreadyHandled = false;
return;
}
alreadyHandled = true;
// Your code here
});
These events don't fire for keys that don't result in text entry — don't you just hate it when you shift-tab back to a form element and the resulting keyup event causes the page's script to move focus forward again?
Additional benefits over key events:
They fire immediately when the key is pressed and not when the key is lifted, as in keyup. This means you don't get a visual delay before any adjustments to the text are made.
They capture other forms of text input like dragging & droppping, spell checker corrections and cut/pasting.
Further reading at Effectively detecting user input in JavaScript.
Update the function:
var func = function(e) {
if(e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40){
txt.val(txt.val().replace(/\s/g, ''));
}
}
try:
$(function() {
var txt = $("#myTextbox");
var func = function(e) {
if(e.keyCode != "37" && e.keyCode != "38" && e.keyCode != "39" && e.keyCode != "40"){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(function(evt){
if(evt.keyCode < 37 || evt.keyCode > 40) {
func;
}
}).blur(func);
});
Something like that should do it. It will run the function if the keycode isn't 37,38,39 or 40 (the four arrow key keycodes). Note that it won't actually stop the cursor position moving to the end when any other key is pressed. For that, you'd need to keep track of the current cursor position. Take a look at this link for jCaret plugin, which can do this

Allow text box only for letters using jQuery?

I want to make a text box allow only letters (a-z) using jQuery.
Any examples?
<input name="lorem" onkeyup="this.value=this.value.replace(/[^a-z]/g,'');">
And can be the same to onblur for evil user who like to paste instead of typing ;)
[+] Pretty jQuery code:
<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>
Accepted answer
The accepted answer may be short, but it is seriously flawed (see this fiddle):
The cursor moves to the end, no matter what key is pressed.
Non-letters are displayed momentarily, then disappear.
It is problematic on Chrome for Android (see my comment).
A better way
The following creates an array of key codes (a whitelist). If the key pressed is not in the array, then the input is ignored (see this fiddle):
$(".alpha-only").on("keydown", function(event){
// Allow controls such as backspace, tab etc.
var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];
// Allow letters
for(var i = 65; i <= 90; i++){
arr.push(i);
}
// Prevent default if not in array
if(jQuery.inArray(event.which, arr) === -1){
event.preventDefault();
}
});
Note that this allows upper-case and lower-case letters.
I have included key codes such as backspace, delete and arrow keys. You can create your own whitelist array from this list of key codes to suit your needs.
Modify on paste only
Of course, the user can still paste non-letters (such as via CTRL+V or right-click), so we still need to monitor all changes with .on("input"... but replace() only where necessary:
$(".alpha-only").on("input", function(){
var regexp = /[^a-zA-Z]/g;
if($(this).val().match(regexp)){
$(this).val( $(this).val().replace(regexp,'') );
}
});
This means we still have the undesired effect of the cursor jumping to the end, but only when the user pastes non-letters.
Avoiding autocorrect
Certain touchscreen keyboards will do everything in their power to autocorrect the user wherever it deems necessary. Surprisingly, this may even include inputs where autocomplete and autocorrect and even spellcheck are off.
To get around this, I would recommend using type="url", since URLs can accept upper and lower case letters but won't be auto-corrected. Then, to get around the browser trying to validate the URL, you must use novalidate in your form tag.
To allow only lower case alphabets, call preventDefault on the event object if the key code is not in the range 'a'..'z'. Check between 65..90 or 'A'..'Z' too if upper case should be allowed.
Or, alternatively use one of the many input mask plugins out there.
See example.
​$(<selector>).keypress(function(e) {
if(e.which < 97 /* a */ || e.which > 122 /* z */) {
e.preventDefault();
}
});​​​​​
// allow only Alphabets A-Z a-z _ and space
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^A-Za-z_\s]/,'') ); } // (/[^a-z]/g,''
);
// allow only Number 0 to 9
$('.numberonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^0-9]/,'') ); } // (/[^a-z]/g,''
);
Demonstrated below to allow only letters [a-z] using Jquery:
$(function() {
$('#txtFirstName').keydown(function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input id="txtFirstName" value="">
Solution described by #dev-null-dweller is working absolutely.
However, As of jQuery 3.0, .bind() method has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
Check deprecated methods list for jQuery 3.0 here: http://api.jquery.com/category/deprecated/deprecated-3.0/
So the solution is to use .on() method instead .bind().
If you need to bind existing elements then the code will be :
$('.alphaonly').on('keyup blur', function(){
var node = $(this);
node.val( node.val().replace(/[^a-z]/g,'') );
});
If you need to bind to dynamic elements the code will be :
$(document).on('keyup blur', '.alphaonly', function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') );
});
You need to bind the event to document or some other element that already exist from the document load.
Hope this is helpful for new version of jQuery.
$("#test").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test1").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test3").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32)||(inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For letters:<input type="text" id="test"> <br>
<br>
For Numbers: <input type="text" id="test1">
<br>
<br>
For Alphanumeric: <input type="text" id="test3">
Thanks to the first answer.. made this..
<input name="lorem" class="alpha-only">
<script type="text/javascript">
$(function()
{
$('.alpha-only').bind('keyup input',function()
{
if (this.value.match(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g))
{
this.value = this.value.replace(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g, '');
}
});
});
</script>
This has some improvements like letters with accents, and changing "blur" for "input" corrects the Non-letters displayed momentarily, also when you select text with the mouse and dragging is corrected..
JQuery function to allow only small and Capital Letters:
Text Field:
<input id="a" type="text" />
JQuery Function:
$('#a').keydown(function (e) {
if (e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
Supports backspace:
new RegExp("^[a-zA-Z \b]*$");
This option will not check mobile. So you can use a jQuery Mask Plugin and use following code:
jQuery('.alpha-field, input[name=fname]').mask('Z',{translation: {'Z': {pattern: /[a-zA-Z ]/, recursive: true}}});
$("#txtName").keypress(function (e) {
var key = e.keyCode;
if ((key >= 48 && key <= 57) || (key >= 33 && key <= 47) || (key >= 58 && key <= 64) || (key >= 91 && key <= 96) || (key >= 123 && key <= 127)) {
e.preventDefault();
}
var text = $(this).val();
$(this).val(text.replace(" ", " "));
});
if (!isValidName(name)) {
//return fail message
} else {
//return success message
}
function isValidName(name) {
var regex = new RegExp("^[a-zA-Z ]+$");
if (regex.test(name)) {
return true;
} else {
return false;
}
}

Categories