trying to paste characters and if it is more than 50 characters ONLY show the first 50 characters. Can anyone tell me what I'm missing?
Here's my code: LIVE DEMO
CKEDITOR.instances.foo.on('paste',function(event){
alert('paste');
var deleteKey = 46;
var backspaceKey = 8;
var keyCode = event.data.keyCode;
if (keyCode === deleteKey || keyCode === backspaceKey)
return true;
else
{
var textLimit = 50;
var str = CKEDITOR.instances.foo.getData();
if (str.length >= textLimit)
// Need to add code here to only show the first 50 characters
return false;
}
});
You can use the WORDCOUNT plugin of CKEditor and you can find the example
https://ckeditor.com/cke4/addon/wordcount
You can use this event.data.dataValue to get and set data from CKEditor
CKEDITOR.instances.foo.on('paste',function(event){
var textLimit = 50;
var str = $(event.data.dataValue).text();
if (str.length >= textLimit) {
event.data.dataValue = str.substr(0 , textLimit);
}
});
http://jsfiddle.net/2ftroyuv/7/
the document show about paste event.
https://docs.ckeditor.com/ckeditor4/latest/guide/dev_clipboard.html#the-paste-event
you could use event.data.dataValue to get the paste content.
code is here:
http://jsfiddle.net/2vzkLb8L/2/
CKEDITOR.instances.foo.on('paste',function(event){
var pasteContent = event.data.dataValue;
var str = CKEDITOR.instances.foo.getData();
var textLimit = 50;
var newcontent = pasteContent + str;
CKEDITOR.instances.foo.setData(newcontent.slice(0,50))
});
Related
I have text, in which on selection I need to replace the text.
Here my requirement is, the space must be remain same after replacing the characters which contains spaces between them.
JavaScript:
function getSel() {
// obtain the object reference for the textarea>
var txtarea = document.getElementById("mytextarea");
// obtain the index of the first selected character
var start = txtarea.selectionStart;
// obtain the index of the last selected character
var finish = txtarea.selectionEnd;
//obtain all Text
var allText = txtarea.value;
// obtain the selected text
var sel = Array(finish - start).join("*");
//append te text;
var newText = allText.substring(0, start) + sel + allText.substring(finish, allText.length);
txtarea.value = newText;
$('#newpost').offset({ top: 0, left: 0 }).hide();
}
$(document).ready(function () {
var position;
$('#newpost').hide();
$('#mytextarea').on('select', function (e) {
$('#newpost').offset(position).show();
var txtarea = document.getElementById("mytextarea");
var start = txtarea.selectionStart;
var finish = txtarea.selectionEnd;
$('#newpost p').text(Array(finish - start).join("*"));
}).on('mousedown', function (e) {
position = { top: e.pageY-5, left: e.pageX};
});
$('#newpost').hide();
});
Here is my plunker
I am getting output as shown in above image but in expected output the space must not be replaced with asterisk .
Use string.replace instead, try this:
console.log('g2ggg gggGG'.replace(/[a-zA-Z0-9]/g, '*'))
Your all string manipulation logic will be only 1 line:
newText = allText.replace(/[a-zA-Z0-9]/g, '*')
I'm not very good at regex so I used a for-loop but maybe this still helps you.
$(document).ready(function () {
$('#mytextarea').on('select', function (e) {
var $output = $("#output");
var $txtarea = $("#mytextarea");
var start = $txtarea[0].selectionStart;
var finish = $txtarea[0].selectionEnd;
var subtext = $txtarea.text().substr(start, finish);
var out = "";
for (var i = 0; i < subtext.length; i++) {
var char = subtext[i];
if (char == " ") {
out += " ";
} else {
out += "*";
}
}
$output.text(out);
});
});
Based on your code you can see the working example in this fiddle:
My html code :-
<input type="text" id="test">
<span class="display"></span>
My jquery code :
$("#test").keyup(function(e){
$('span.display').text(formatCurrency($(this).val()));
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Demo and full code is like this : https://jsfiddle.net/oscar11/nbLbb037/
I want the input text can enter this : -10000000
And the result who displayed in class display is : -10.000.000
How can I add minus (-) sign?
Need to change code like below:-
output = output.reverse();
if(output[1] == '.'){
output.splice(1, 1);
formatted = output.join("");
}else{
formatted = output.join("");
}
And every thing will be fine.
Example:-
$("#test").keyup(function(e){
$('span.display').text(formatCurrency($(this).val()));
this.value = this.value.replace(/[^0-9\.-]/g,'');
});
// format currency on pagu and revisi
var formatCurrency = function(num){
var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null;
if(str.indexOf(",") > 0) {
parts = str.split(",");
str = parts[0];
}
str = str.split("").reverse();
for(var j = 0, len = str.length; j < len; j++) {
if(str[j] != ".") {
output.push(str[j]);
if(i%3 == 0 && j < (len - 1)) {
output.push(".");
}
i++;
}
}
output = output.reverse();
if(output[1] == '.'){
output.splice(1, 1);
formatted = output.join("");
}else{
formatted = output.join("");
}
return(formatted + ((parts) ? "," + parts[1].substr(0, 1) : ""));
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">
<span class="display"></span>
adding a minus sign is very easy, just replace
this.value = this.value.replace(/[^0-9\.]/g,'');
with following
this.value = this.value.replace(/[^0-9\.-]/g,'');
updated js fiddle is https://jsfiddle.net/nbLbb037/3/
But. You need to use regular expression test to verify exact currency test. Try exploring js regular expression test for your "formatCurrency" function. Of course thats purly upto you. Current solution will let you move further.
I have updated the regular expression js code on fiddle. Refer to https://jsfiddle.net/nbLbb037/5/
I managed to make this little jquery function to count the number of words entered in textarea field.
here is the fiddle
and here is the code:
JQUERY:
$(document).ready(function()
{
var wordCounts = {};
$("#word_count").keyup(function() {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
$.each(wordCounts, function(k, v) {
finalCount += v;
});
$('#display_count').html(finalCount);
am_cal(finalCount);
}).keyup();
});
and here is html code
<textarea name="txtScript" id="word_count" cols="1" rows="1"></textarea>
Total word Count : <span id="display_count">0</span> words.
how can i make modifications in it to have the output like this
Total word Count : 0 words. Words left : 200
and when it reach 200 words it shall not allow to either paste, or type more words in the textarea field, in jquery? i.e. it shall restrict user to type exactly 200 words not more than that.
Please help.
Thanks a lot in advance.
EDIT: The modification is needed in this code only, as i am very well aware of the plugins, but they may interfere with the main code.
Using return false to stop keyup events doesn't block the event, because in this case the event has already fired. The keyup event fires when the user releases a key, after the default action of that key has been performed.
You will need to programmatically edit the value of the textarea you have as #wordcount:
$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = 0;
if ((this.value.match(/\S+/g)) != null) {
words = this.value.match(/\S+/g).length;
}
if (words > 200) {
// Split the string on first 200 words and rejoin on spaces
var trimmed = $(this).val().split(/\s+/, 200).join(" ");
// Add a space at the end to make sure more typing creates new words
$(this).val(trimmed + " ");
}
else {
$('#display_count').text(words);
$('#word_left').text(200-words);
}
});
});
http://jsfiddle.net/k8y50bgd/
I would do it like this ?
$("#word_count").on('keydown', function(e) {
var words = $.trim(this.value).length ? this.value.match(/\S+/g).length : 0;
if (words <= 200) {
$('#display_count').text(words);
$('#word_left').text(200-words)
}else{
if (e.which !== 8) e.preventDefault();
}
});
FIDDLE
A simple plugin can be found here:
Simple Textarea Word Counter using jQuery
Adding a simple if condition will solve your problem.
$.each(wordCounts, function(k, v) {
if(finalCount <= 200) {
//Todos
}
else {
return false; //prevent keyup event
}
});
$(document).ready(function(){
$("textarea").on('keyup',function(){
var value = $('textarea').val();
var wordCount = 0;
if(value == ""){
$('textarea').empty();
}
else{
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
}
if(wordCount > 25){
var trimmed = $(this).val().split(/\s+/,25).join(" ");
$(this).val(trimmed + " ");
}
else{
$('#display_count').html(25- wordCount +" words left");
}
});
});
You can use positive lookahead regexes to preserve the whitespace - so that returncodes and tabs are not collapsed to a single space. Something like this:
var wordLimit = 5;
var words = 0;
var jqContainer = $(".my-container");
var jqElt = $(".my-textarea");
function charLimit()
{
var words = 0;
var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = jqElt.val()[trimmed.length];
jqElt.val(trimmed + lastChar);
}
$('.word-count', jqContainer).text(words);
$('.words-left', jqContainer).text(Math.max(wordLimit-words, 0));
}
jqElt.on("keyup", charLimit);
charLimit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
<textarea class="my-textarea"></textarea>
<span class="words-left"></span> words left
<div>
Here is the final solution.
(function(){
$("textarea").after("<p>Number of words: <span class='count'>0</span>/10</p>");
$("textarea").keypress(function(){
var words = $.trim($(this).val()).split(" ").filter(function(word){
return $.trim(word).length > 0
});
var wordlength = words.length;
$(".count").text(wordlength);
if(wordlength > 10){
alert("Please do not enter more than 10 words");
$(this).val( words.splice(0,10).join(" "));
return false;
}
})
})
I have the following bind on keyup which alerts if they go over 150 characters, but you can just press okay and keep typing and then just keep pressing okay.
I want to crop them at 150 words (not characters) and if they type over it, remove the extras. But I can't seem to figure out how to do it, I can figure out characters. But not words.
jQuery('textarea').keyup(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > 150) {
jQuery(".word_count span").text("150");
return alert("You've reached the maximum allowed words.");
} else {
return jQuery(".word_count span").text(wordcount);
}
});
/**
* jQuery.textareaCounter
* Version 1.0
* Copyright (c) 2011 c.bavota - http://bavotasan.com
* Dual licensed under MIT and GPL.
* Date: 10/20/2011
**/
(function($){
$.fn.textareaCounter = function(options) {
// setting the defaults
// $("textarea").textareaCounter({ limit: 100 });
var defaults = {
limit: 100
};
var options = $.extend(defaults, options);
// and the plugin begins
return this.each(function() {
var obj, text, wordcount, limited;
obj = $(this);
obj.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">Max. '+options.limit+' words</span>');
obj.keyup(function() {
text = obj.val();
if(text === "") {
wordcount = 0;
} else {
wordcount = $.trim(text).split(" ").length;
}
if(wordcount > options.limit) {
$("#counter-text").html('<span style="color: #DD0000;">0 words left</span>');
limited = $.trim(text).split(" ", options.limit);
limited = limited.join(" ");
$(this).val(limited);
} else {
$("#counter-text").html((options.limit - wordcount)+' words left');
}
});
});
};
})(jQuery);
Load that up and then you can use the following to make it work:
$("textarea").textareaCounter({ limit: 100 });
http://bavotasan.com/2011/simple-textarea-word-counter-jquery-plugin/
If you want to prevent the typing itself (when count > 150) you can do as following:
Use keypress instead of keyup
Instead of return alert() first do an alert() and then return false;
You may also want to add change (or blur) event handler to handle text pasting.
var maxWords = 150;
jQuery('textarea').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
jQuery(".word_count span").text("" + maxWords);
alert("You've reached the maximum allowed words.");
return false;
} else {
return jQuery(".word_count span").text(wordcount);
}
});
jQuery('textarea').change(function() {
var words = $(this).val().split(/\b[\s,\.-:;]*/);
if (words.length > maxWords) {
words.splice(maxWords);
$(this).val(words.join(""));
alert("You've reached the maximum allowed words. Extra words removed.");
}
});
Fiddle here
Check jQuery: Count words in real time
and this example: http://jsfiddle.net/gilly3/YJVPZ/1/
Then, if you want to cut the extra words... you could do something like:
var maxWords = 10;
if(finalCount > maxWords){
$("#a").val(a.value.slice(0,-2)); // the -2 is to remove the extra space at the end
};
Here is a working example http://jsfiddle.net/YJVPZ/80/
Hope it helps, Good Luck!
Try this function. The value argument should be your textarea value.
jQuery('textarea').val();
function wordcount(value)
{
value = value.replace(/\s+/g," ");
var andchr = value.split(" & ").length - 1;
var char_count = value.length;
var fullStr = value + " ";
//word count for regional language
v = value.split(' ');
var word_count1 = v.length;
var cheArr = Array('#','.','"',"'",'_','-','+','=',';','&','*','\(','\)','{','}','[','}','|','\\','\,','/');
for(i=0; i<=cheArr.length; i++)
{
word_count1 = word_count1 + value.split(cheArr[i]).length - 1;
}
//word count for all languages
var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
var splitString = cleanedStr.split(" ");
var word_count = (splitString.length - 1) + andchr;
if(word_count1 > word_count)
{
word_count = word_count1;
}
if(value == '' || value == null || typeof(value) == 'undefined'){
word_count = 0;
}
alert(word_count);
}
$("textarea").keyup(function(){
var obj = $(this);
var maxLen = 150;
var val = obj.val();
var chars = val.length;
if(chars > maxLen){
obj.val(val.substring(0,maxLen));
}
});
Register to these events:
$('textarea').on('paste cut keydown', function(){...});
What Im trying to do is - i dont know the name maybe - a Prediction Help Inputter inside a textarea. It uses jquery autocomplete. When the user types '[[g ' inside textarea (id=test), a input with autocomplete is opened (id=example), so it search in 'data'. When the user find the desired data, he must press Shif+Enter to insert the data into the textarea, closing with ']]'.
How could I find the position of the carret to make the input appears near there?
I dont want to find the index of the carret, but something like the x y absolute position.
What do you suggest me?
Code above:
<textarea onkeydown="predicao(this);" cols="40" rows="10" id="test" onfocus="this.focus()"></textarea>
<input id="example" style="display: none;" onkeyup="insert(this, event);"/>
<script language="Javascript">
<!--
function predicao(objeto){
comprimento = objeto.value.length;
var antipenultimo = comprimento - 4;
var input = objeto.value.substring(antipenultimo,comprimento);
var output = "";
for(i=0; i<input.length; ++i){
if(output != "") output += ", ";
output += input.charCodeAt(i);
}
if (output == "91, 91, 103, 32"){
var preditor = document.getElementById('example');
preditor.value = '';
preditor.style.display = 'block';
preditor.focus();
preditor.select();
}
}
function insert(objeto, evt){
var e = evt || event;
var code = e.keyCode || e.which;
if(e.shiftKey && code == '13') {
var texto = document.getElementById('test').value;
texto += objeto.value+']]';
document.getElementById('test').focus();
document.getElementById('test').value = texto;
objeto.style.display = 'none';
}
}
$(document).ready(function(){
var data = "Afrikaans Català Deutsch English Esperanto Suomi Français Galego Hrvatski Magyar Bahasa Indonesia Italiano Basa Jawa".split(" ");
$("#example").autocomplete(data);});
</script>
Something like:
var pos = $('textarea').caret(); // using caret plugin...
var lines = $('textarea').val().slice(0, pos).replace(/\t/g, ' ').split('\n');
var y = lines.length;
var x = lines[y-1].length;
Should work reasonably well for fix-width fonts.
If you're looking to do it via JS only:
function doGetCaretPosition (ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
Courtesy: http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
Demo: http://demo.vishalon.net/getset.htm