Ckeditor character limitation with charcount plugin - javascript

How can i prevent users to enter new characters after max character limit is reached ?
Ckeditor charcount plugin just shows me the remaining characters, i want it to stop at 0. But it goes minus integers.
Here's my html code.
<textarea id="myTextEditor1" name="myTextEditor"></textarea>
<script type="text/javascript">
CKEDITOR.replace('myTextEditor1', {
height: 200,
extraPlugins: 'charcount',
maxLength: 10,
toolbar: 'TinyBare',
toolbar_TinyBare: [
['Bold','Italic','Underline'],
['Undo','Redo'],['Cut','Copy','Paste'],
['NumberedList','BulletedList','Table'],['CharCount']
]
});
</script>
Do i have to use onChange plugin ? If i have to how can i limit users entering new characters ?

I used the ckeditor jQuery adapter for this.
<textarea id="myTextEditor1" name="myTextEditor"></textarea>
<script type="text/javascript">
$(function () {
var myEditor = $('#myTextEditor1');
myEditor.ckeditor({
height: 200,
extraPlugins: 'charcount',
maxLength: 10,
toolbar: 'TinyBare',
toolbar_TinyBare: [
['Bold','Italic','Underline'],
['Undo','Redo'],['Cut','Copy','Paste'],
['NumberedList','BulletedList','Table'],['CharCount']
]
}).ckeditor().editor.on('key', function(obj) {
if (obj.data.keyCode === 8 || obj.data.keyCode === 46) {
return true;
}
if (myEditor.ckeditor().editor.document.getBody().getText().length >= 10) {
alert('No more characters possible');
return false;
}else { return true; }
});
});
</script>
The keyCode check is to allow backspace and delete key presses. To use the jQuery adapter, don't forget to insert it:
<script src="/path-to/ckeditor/adapters/jquery.js"></script>

Related

Jquery: An alternate method for fromcharcode() to convert integer to character

I'm coding a chat box. And the Characters that I enter, is not reflected as it is.
This is basically the code I'm using.
$(document).ready(function() {
$(".entry").keydown(function(event) {
console.log(String.fromCharCode(event.which));
});
});
And so when I type (lower-case) "a", console tab shows me "A".
special characters will not get reflected unless I create separate condition for it.
Could someone help me with a different function which does it all by itself, and returns a string as entered by the user. Or a different approach to this challenge all together. Thanks.
Actual code - chat.js
var str='';
$(document).ready(function() {
$(".entry").keydown(function(event) {
console.log(event.which);
if (event.which === 13 && event.shiftKey === false) {
console.log(str);
event.preventDefault();
} else {
var c = event.which;
str = str.concat(String.fromCharCode(c));
}
});
});
So basically the every character entered would get concated to the string. and Enter key would dump the text to console.
It's seems that trying to get the value of event.which in keydown event could lead you to a wrong ascii code (What you need to pass to String.fromCharCode).
See https://stackoverflow.com/a/10192144/3879872
I don't know if it fits your needs, but you could try:
$(document).ready(function(){
$(".entry").keypress(function(event) {
console.log(String.fromCharCode(event.which));
});
});
(Note the use of keypress instead of keydown)
EDIT: Added working Demo
var str = '';
$(document).ready(function() {
$(".entry").keypress(function(event) {
console.log(event.which);
if (event.which === 13 && event.shiftKey === false) {
console.log(str);
event.preventDefault();
} else {
var c = event.which;
str = str.concat(String.fromCharCode(event.which));
}
console.log('Formated Text', str);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="entry"></textarea>

how avoid 0 to be entered in first position text box using javascript?

i know its possible duplicate. but existing solution is not working out for me.
field should accept like below.
valid - 123,33.00,
100,897,99,
8000
10334
9800,564,88.36
invalid - 001, 0, 01234234, -123, 1.44, .99, 12asdf, 12ASDF, asdf123, ASDF34
codes so far. below code is in ngOninit()
$("#amoutField").on("keypress keyup", function() {
if ($(this.amtField).val() == '0') {
$(this.amtField).val('');
}
});
another method am having is to restrict range
avoidZero(e, field) {
if (field.name === "amoutField ") {
e = (parseInt(e) == 0) ? 0 : e;
this.amoutField = e.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$("#amoutField").val(this.amoutField);
}
}
<input class="wdh100p" type="text" id="amoutField" name="amoutField " value="" maxlength="5"
[ngModel]="amoutField " (ngModelChange)="avoidZero($event, amts)">
You can use a regular expression and simply remove all the leading zeros when the input value changes...
$("#amountField").on("input", function() {
this.value = this.value.replace(/^[0]*/, "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="amountField" />
Note: Using the input event covers all possible ways the value of the input can change (copy/paste, drag/drop etc.)
You need to separate the events to handle different situations:
Situations
User typing zero at first position
User dragging value from another field to this field.
User typing number and then typing zero at first position.
$("#amoutField").on("keydown", function(e) {
if ($(this).val().trim().length === 0 && e.keyCode === 48) {
e.preventDefault();
}
}).on("keyup", function() {
handleKeyupFocus(this);
}).on('focus', function() {
handleKeyupFocus(this);
}).on('drop', function() {
var $self = this;
setTimeout($.proxy(function() {
handleKeyupFocus($self);
}), 0);
});
var handleKeyupFocus = function(target) {
while ($(target).val().startsWith("0")) {
$(target).val($(target).val().substring(1));
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Try to drag, paste zeros from another field, clipboard, Etc.</p>
<input id="amoutField">
Are you sure that "0" is an invalid case?
If not, the simplest approach is:
function isValid(text) {
return parseFloat(text).toString() === text;
}
Test:
var test = ["-123", "238", "100", "10336", "101010", "10001", "-001", "0", "01234234"];
var results = test.map(t => isValid(t));
Output:
[ true, true, true, true, true, true, false, true, false ]
Bonus: in case zero is an invalid case, just filter it out.
function isValid(text) {
var numericValue = parseFloat(text).toString();
return numericValue === text && numericValue !== "0";
}

Restricting users from inserting spaces, capitol letters, first value as int in textbox using jquery

I have a form in which I want users to only put alphabets, numbers
I want to restrict them from
Using the number as first value Eg. 1abc
Using Capitol letters Eg. 1ABc
Using Spaces Eg. 1 ab CD d5
I only want like abc1 OR a1bc OR f25fhgfh45w
I tried http://jsfiddle.net/m7QrG/506/ but it didn't help me out.
You can use RegExp /^\d|[A-Z\s]+/g to match digit at beginning of string or uppercase letters or space, remove i flag and $ anchor, use input event to also handle user pasting at <input> element
$('.alphaonly').on('input', function() {
$(this).val(function(i, val) {
return val.replace(/^\d|[A-Z\s]+/g, '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="lorem" class="alphaonly">
After observing your question and your comments with #guest271314 I came up to with the solution:
$(function() {
var haveFirst = false;
$('.alphaonly').on('keypress', function (event) {
if( $(this).val().length === 0 ) {
haveFirst = false;
}
var regex = new RegExp("^[a-z0-9_]+$");
var first = new RegExp("^[a-z]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if(!first.test(key) && haveFirst == false){
event.preventDefault();
return false;
}else if(regex.test(key)){
haveFirst = true;
}
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="lorem" class="alphaonly">
In hoping it will work as you want!

How to edit the correct phone number in my script?

I have this sample:
link
CODE HTML:
<label for="primary_phone">Primary Phone Number<span class="star">*</span></label>
<br>
<input type="text" name="primary_phone" id="primary_phone" class="_phone required-input" value="" maxlength="10">
CODE CSS:
.invalid{
border:1px solid red !important;
}
.valid{
border:1px solid green !important;
}
CODE JS:
function phoneFormat(){
$( "._phone" ).on('blur change', function() {
text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
var testt=$(this).val().match(text);
if($(this).val()=='' || $(this).val().match(text) || $(this).val().length == 0)
{
$(this).removeClass('valid').addClass('invalid');
}
else{
$(this).removeClass('invalid').addClass('valid');
}
$(this).val(text);
});
}
$( "#primary_phone" ).blur(function() {
phoneFormat();
});
I put a script that arranges text format
for example, we can add this number :
1234567890
After calling script appears next form (what is right)
(123) 456-7890
The problem is when you want to edit my phone number ... if you want to delete the last two numbers because I put the following code maxlength="10"
I want the user can not write more than 10 characters.
How do I fulfill both requirements.
If something is not explained well I'll do an edit to this post
Thanks in advance!
Just remove all special characters when you focus in on the input box:
$("#primary_phone").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,'');
$(this).val(value);
});
Now when you click out of the input box, your original function to format the number comes in to play :)
Working fiddle : https://jsfiddle.net/reko91/gto0qeyx/2/
I would set a higher maxlength (say 15) and bind the input to keypress.
Inside the event you can check the keyCode against a set of allowed ones and suppress the event (entry of the character) otherwise.
I would also suppress the entry of numbers if we already have 10 (with one exception: if the user selected (marked) a portion of the input and that selection contains numbers.
var alwaysAllowed = [32, 40, 41, 45]; // [" ","(",")","-"]
function keyCode(keyCode) {
if (alwaysAllowed.indexOf(keyCode) !== -1) {
return "allowed";
} else if (keyCode >= 48 && keyCode <= 57) {
// 0 - 9
return "number";
} else {
// any other character
return false;
}
}
function countNumbers(text) {
// return the number of characters [0-9] in the string "text"
var counter = 0;
for (var i = 0; i < text.length; i++) {
if (parseInt(text[i]) >= 0 && parseInt(text[i]) < 10) {
counter++;
}
}
return counter;
}
$primaryPhone.on("keypress", function () {
var keyCodeEvaluation = keyCode(event.keyCode);
if (keyCodeEvaluation === false) {
event.preventDefault();
} else if (keyCodeEvaluation === "number") {
var value = this.value,
counter = countNumbers(value.substring(this.selectionStart, this.selectionEnd));
//
if (counter === 0 && countNumbers(value) > 9) {
event.preventDefault();
}
}
});
This would allow the user to edit (or write) the phonenumber with your format applied.
MORE IMPORTANTLY
You should rewrite your phoneFormat() function.
Each execution adds another event listener. The first time you change the input value it executes one time. Then two times, three times and so forth.
You should also store objects you use repeatedly in a variable, e.g. $( this ) (creating the same jQuery object each time is a performance killer).
Here is a working example that should cover most of your use cases.

Limit the number of newline of dynamic textarea in jquery

I'm trying to limit the number of newline that can be enter in a dynamic textarea, but the codes I made is not working. I need to set atleast 4 newlines that the user can make. Also I set the maxlength to 40 characters.
here is my codes.
$(document).ready(function(){
$("[name='memo[]']").each(function(){
$(this).keydown(function() {
newLines = $(this).val().split("\n").length;
$(this).text(newLines);
if(e.keyCode == 13 && newLines >= 4) {
alert("Exceed");
return false;
}
});
});
});
Try this:
$(document).ready(function() {
$("[name='memo[]']").each(function() {
var textarea = $(this);
textarea.attr('maxlength', 40);
textarea.keydown(function(e) {
var newLines = textarea.val().split(/\r*\n/).length;
if (e.keyCode === 13 && newLines >= 4) {
e.preventDefault();
}
});
});
});
UPDATE:
Dont alert and the code works fine. Demo link is: http://jsfiddle.net/bobkhin/nJWk2/
get the lines in text area with the below example code and try...
String.prototype.lines = function() { return this.split(/\r*\n/); }
String.prototype.lineCount = function() { return this.lines().length; }

Categories

Resources