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(){...});
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:
I have a function which is successfully returning a ul list of random numbers between 1 and 100, and it places the numbers on the user's clipboard. This is just for IE but this isn't a problem.
This issue is that the resulting text on the clipboard is retaining the li tags like below. Is there a way to remove these tags from the data before it hits the clipboard?
<LI>68</LI>
<LI>97</LI>
<LI>94</LI>
<LI>43</LI>
<LI>45</LI>
<LI>65</LI>
The JS code:
function ReturnRandomNumbers() {
var howManyInt = parseInt(document.getElementById("txtMultiples").value);
var listNumbers = document.getElementById("listNumbers");
var i = 0;
if (howManyInt < 101 && howManyInt > 0) {
listNumbers.innerHTML = "";
while (i < howManyInt) {
AddItemToList(randomNumber());
i++;
}
window.clipboardData.setData("text",listNumbers.innerHTML);
alert(listNumbers.innerHTML);
} else {
alert("Value must be between 1 and 100");
}
}
function AddItemToList(item) {
var ol = document.getElementById("listNumbers");
var li = document.createElement("li");
li.appendChild(document.createTextNode(item));
ol.appendChild(li);
}
var str = "<LI>68</LI>\n<LI>97</LI>\n<LI>94</LI>\n<LI>43</LI>\n<LI>45</LI>\n<LI>65</LI>"
or
var str = listNumbers.innerHTML;
You want to strip the li tags from the string, you can do a regex match and replace
var stripped = str.replace(/<\/*LI>/g,'');
Which will give
"68
97
94
43
45
65"
Pass it to your clipboard window.clipboardData.setData("text",stripped);
Modify your ReturnRandomNumbers() function into this:
function ReturnRandomNumbers()
{
var howManyInt = parseInt(document.getElementById("txtMultiples").value);
var listNumbers = document.getElementById("listNumbers");
var i = 0;
var strForClipboard = '';
if (howManyInt < 101 && howManyInt > 0) {
listNumbers.innerHTML = "";
while (i < howManyInt) {
var randNumb = randomNumber();
strForClipboard += (strClipboard ? '\n' : '') + randNumb;
AddItemToList(randNumb);
i++;
}
window.clipboardData.setData("text",strForClipboard);
alert(strForClipboard);
}
else {
alert("Value must be between 1 and 100");
}
}
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 think i'm missing something or have a silly error. I'm trying to get the counter going for textarea & for some reason length of textarea value is always zero. Here is my same code for View:
#Html.TextAreaFor(x => x.Description, new { #maxlength = "4000", #onkeyup = "countChar(this)" })
#Html.Label("", " ", new { #id = "lblcount" })
my corresponding javascript is:
function countChar(val) {
var max = 4000;
var len = $("#txtDescription").val().length;
if (len >= max) {
$('#lblcount').text(' you have reached the limit');
$('#lblcount').attr("class", "lblCountRed");
} else {
var ch = max - len;
$('#lblcount').text(ch + ' characters left');
$('#lblcount').attr("class", "lblCountGreen");
}
};
The above code always sets label text to "4000 characters left" irrespective of number of characters I type inside textarea.
I would really NOT advice you to use inline JavaScript but here is what the function should be:
function countChar( elem ) {
var max = 4000,
len = elem.value.length,
lbl = $('#lblcount');
if(len >= max) {
lbl.text(' you have reached the limit')
.addClass("lblCountRed").removeClass('lblCountGreen');
} else {
var ch = max - len;
lbl.text(ch + ' characters left')
.addClass("lblCountGreen").removeClass('lblCountRed');
}
}
If you wanted to accomplish this without inline JavaScript, you would:
remove #onkeyup = "countChar(this)"
then use the following code:
-
$(document).ready(function() {
$("#Description").on('keyup', function() {
var max = 4000,
len = this.value.length,
lbl = $('#lblcount');
if(len >= max) {
lbl.text(' you have reached the limit')
.addClass("lblCountRed").removeClass('lblCountGreen');
} else {
var ch = max - len;
lbl.text(ch + ' characters left')
.addClass("lblCountGreen").removeClass('lblCountRed');
}
});
});
You used wrong selector. Your textarea ID is Description but you used txtDescription. You should use
var len = $("#Description").val().length;
instead of
var len = $("#txtDescription").val().length;
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;
}
})
})