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;
}
})
})
Related
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))
});
I'm trying to make a code that'll change the color of an output div as the
user types in an input. I want the color to change based on sentence length
and without the use of a button.
Here's the javascript code I have so far:
function highlight() {
var input = document.getElementById("myInput").value;
var output = document.getElementById("output").innerHTML = input;
}
var sentence = input.split( /[^\.!\?]+[\.!\?]+/g );
var count = sentence.split(" ").length;
console.log(count);
if (count < 3) {
output.style.backgroundColor = ("red");
} else if (count < 5) {
output.style.backgroundColor = ("green");
} else if (count < 15) {
output.style.backgroundColor = ("blue");
}
If your trying to make the hightlight() function run after each keystroke, use the oninput attribute
<input id="myInput" oninput="highlight()">
Also, sentence should be defined like this:
var sentence = input.split(/[^\.!\?]+[\.!\?]+/g)[0];
// get first item ^^^
UPDATE
The current behavior of the program is this:
The hightlight function is called on each keystroke
The length of the sentence is determined by the number of words composing it.
If the input contains multiple sentences, the length is the total number words contained by all the sentences.
Take a look at the snippet below:
function highlight() {
var input = document.getElementById("myInput").value;
var output = document.getElementById("output");
output.innerHTML = input;
//var sentence = input.split(/[^\.!\?]+[\.!\?]+/g)[0];
var sentences = input.split(/[.!?]/g);
var count = 0;
sentences.forEach(function(sentence) {
count += sentence.split(' ').length;
});
console.log(count);
if (count < 3) {
output.style.backgroundColor = ("red");
} else if (count < 5) {
output.style.backgroundColor = ("green");
} else if (count < 15) {
output.style.backgroundColor = ("blue");
}
}
<input id="myInput" oninput="highlight()">
<span id="output"></span>
UPDATE #2
As per the OP's request, the desired behavior has been modified:
highlight() is called on every keystroke
The input text is split into sentences
Highlighting is applied independently to each sentence
One <span> tag is created any styled for each sentence
There are two main changes I made.
A <span> tag is dynamically created for each sentence with document.createElement.
Highlighting is applied individually to each <span> instead of to a single <p id="output"></p> tag.
Snippet:
function highlight() {
var input = document.getElementById("myInput").value;
var output = document.getElementById("output");
output.innerHTML = ""; // clear all output
//var sentences = input.split(/[.!?]\s*/g);
var sentences = input.match(/(.+?(?:[.!?]|$))/g);
console.log(sentences);
sentences.forEach(function(sentence) {
sentence = sentence.trim(); // remove leading or trailing whitespace
if (sentence === "") return; // skip empty sentences
var count = sentence.split(' ').length;
var t = document.createElement('span');
t.className = "sentence";
t.textContent = sentence;
if (count < 3) {
t.style.backgroundColor = "#dd6";
} else if (count < 5) {
t.style.backgroundColor = "#5f9";
} else if (count < 15) {
t.style.backgroundColor = "#59f";
}
output.appendChild(t);
});
}
.sentence {
margin-right: 4px;
border-radius: 2px;
padding: 2px;
}
<input id="myInput" oninput="highlight()">
<div id="output">
</div>
I have inserted a text inside the placeholder.And it's working properly.Now After appearing the text, I want the cursor to go to a specific point(here doubts) and correct the misspelled word(doubts to doubt).
How to do it ? Can you show me any example I want to do in the project.
Code###
var txt = "Please write your message.If any doubts, don't hesitate to make a questions !";
var timeOut;
var txtLen = txt.length;
var char = 0;
$('textarea').attr('placeholder', '|');
(function typeIt() {
var humanize = Math.round(Math.random() * (200 - 30)) + 30;
timeOut = setTimeout(function() {
char++;
var type = txt.substring(0, char);
$('textarea').attr('placeholder', type + '|');
typeIt();
if (char == txtLen) {
$('textarea').attr('placeholder', $('textarea').attr('placeholder').slice(0, -1)) // remove the '|'
clearTimeout(timeOut);
}
}, humanize);
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<textarea cols="50" rows="15" placeholder=""></textarea>
</form>
First, add another variable to hold the the modified, typo-free string so we can still iterate through the original. This new variable will be used to display text.
var modified_txt = "";
If you know the position in the string of the typo you can make an object of the position of the typos to check.
//Positions in the txt string where typos exist
var typos = {
38: {},
25: {}
}
As your char counter increases you can check it against the object.
var test = typos[char];
if (test !== undefined) {
//Typo found do something with it
}
In this case I opted to write 2 new functions, 1 for adding characters and 1 for deleting them
function deleteCharacter(text) {
text = text.substring(0, text.length - 1);
return text;
}
function addCharacter(text, character_added) {
text = text + character_added;
return text;
}
I also decided to have one of the typo object properties be a function, so we can organize our typos and do what we want within the typo object.
var typos = {
38: {
error: 's',
correction: function(text) {
var temp = deleteCharacter(text);
$('textarea').attr('placeholder', temp + '|');
return temp;
}
}
}
Now we can make a function call when a typo is found.
if (test !== undefined) {
//Typo found do something with it
setTimeout(function() {
var chunk_one = test.correction(modified_txt);
modified_txt = chunk_one;
char++;
typeIt();
}, humanize());
} else { //If no typos are found then move to the next character
setTimeout(function() {
char++;
typeIt();
}, humanize());
}
Full working code at codepen
i can find text of an element by using this code.but i want to find a single word any where in my page if mouse hovers on that word for certain time.
$(document).bind("mouseover", function (e) {
var event = e;
setTimeout(function () { $(event.target).contents().each(function(index, elem) {
if( elem.nodeType === 3 && $.trim(elem.nodeValue).length ) {
var text = $.trim(elem.nodeValue);
text = text.split(" ");
console.log($.trim(elem.nodeValue));
//alert($.trim(elem.nodeValue));
return false;
}
});
}, 5000);
});
This is likely not the best code ever, but it might get you on the right track, going off of andyb's comment.
Something like
$(".first").on("hover",function(){
var words = $(this).text().split(" ");
var fullText = "";
for(i=0;i<words.length;i++){
words[i] = "<span>"+words[i]+"</span> ";
fullText += words[i];
}
$(this).text("").append(fullText);
$(this).children("span").on("hover", function(){
$(".second").text($(this).text());
});
});
Though looking at the working example is your best option.
$(document).bind("mouseover", function (e) {
var event = e;
setTimeout(function () { $(event.target).contents().each(function(index, elem) {
if( elem.nodeType === 3 && $.trim(elem.nodeValue).length ) {
var text = $.trim(elem.nodeValue);
text = text.split(" ");
var words = (elem.nodeValue).split(" ");
var fullText = "";
for(i=0;i<words.length;i++){
words[i] = "<span>"+words[i]+"</span> ";
fullText += words[i];
}
$(event.target).html("").append(fullText);
$(event.target).children("span").on("hover", function(){
//$(".second").text($(this).text());
console.log($(this).text());
});
console.log($(event.target).html());
return false;
} //alert($(event.target).text()+$(event.target).html());
});},
10000);
});
now my code is this....and working well.but the problem is that now, if an anchor tag or tag have chailds tag or span tag after some text, it just picks up the text parse it and neglect the child nodes.......:(....i want to pick these child nodes...put span tags for every word and than the outer text
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(){...});