I'm working on validating my tinymce editor. At the moment I have it validating by character count which works, but I would like to turn it into sort of like a word count since this is supposed to be the body of an article. So basically they cannot submit an article that is just a few words.
At the moment I have this
setup : function(ed) {
ed.onInit.add(function(ed, evt) {
tinymce.dom.Event.add(ed.getBody(), 'focusout', function(e, t) {
var con = tinyMCE.activeEditor.getContent();
var len = con.replace(/(<([^>]+)>)/ig,"").length;
if(len <=100){
$('.storyError').text('An artical has to have at least 100 words!');
}else{
$('.storyError').text(' ');
}
});
});
}
after my init that is and this does work, I would just like to count the words instead of the characters. Some help would be much appreciated!
I'm working on validating my tinymce editor. At the moment I have it validating by character count which works, but I would like to turn it into sort of like a word count since this is supposed to be the body of an article. So basically they cannot submit an article that is just a few words.
At the moment I have this
setup : function(ed) {
ed.onInit.add(function(ed, evt) {
tinymce.dom.Event.add(ed.getBody(), 'focusout', function(e, t) {
var con = tinyMCE.activeEditor.getContent();
var len = con.replace(/(<([^>]+)>)/ig,"").length;
if(len <=100){
$('.storyError').text('An artical has to have at least 100 words!');
}else{
$('.storyError').text(' ');
}
});
});
}
after my init that is and this does work, I would just like to count the words instead of the characters. Some help would be much appreciated!
Share Improve this question edited Jun 15, 2013 at 20:04 zazvorniki asked Jun 15, 2013 at 19:09 zazvornikizazvorniki 3,61223 gold badges78 silver badges126 bronze badges5 Answers
Reset to default 3here you go, just replace the selector and take the text however you need :
var count = 0;
function fn(){
count++;
return ' ';
}
var x= $('textarea').text().trim();
console.log(x);
x= x.replace(/[\s]+/ig,fn);
//x is now filtered out of extra spaces too !
var words = count+1;
count = 0;
console.log(words);
JSFiddle
in your case it will be :
var count = 0;
function fn(){
count++;
return ' ';
}
setup : function(ed) {
ed.onInit.add(function(ed, evt) {
tinymce.dom.Event.add(ed.getBody(), 'focusout', function(e, t) {
var con = tinyMCE.activeEditor.getContent().trim();
con = con.replace(/[\s]+/ig,fn);
//var len = con.replace(/(<([^>]+)>)/ig,"").length;
var words = count+1;
count = 0;
if(words <=100){
$('.storyError').text('An artical has to have at least 100 words!');
}else{
$('.storyError').text(' ');
}
});
});
}
or to make everything in one line use this (but it won't filter extra spaces out):
var words = con.trim().split(/\s+/).length;
It's pretty easy:
- Create some dummy element in DOM.
- Let this element hold your data.
- Use
Node.textContent
orNode.innerText
to extract textual content from your data (without tags etc.) - Split text and count words.
Working example:
var data = '<p>First paragraph <strong>with strong</strong></p>',
dummy = document.createElement( 'div' );
dummy.innerHTML = data;
console.log( ( dummy.textContent || dummy.innerText ).split( /\s+/ ).length );
>>> 4 // no "strong", "p" etc, just text
More about Node.textContent on MDN.
for tinymce 4.1.4
$('#ContentPlaceHolder1_txtTitle').tinymce({
theme: "modern",
plugins: "wordcount code charmap paste",
toolbar1: "bold italic underline strikethrough | removeformat | subscript superscript | charmap | cut copy paste | undo redo | code visualblocks visualchars",
paste_auto_cleanup_on_paste: true,
paste_remove_styles: true,
paste_remove_styles_if_webkit: true,
paste_strip_class_attributes: true,
menubar: false,
toolbar_items_size: 'large',
forced_root_block: "",
max_word: 5,
setup: function (ed) {
ed.on('keyup', function (e) {
var writtenWords = $('.mce-wordcount').html();
writtenWords = writtenWords.replace("Words: ", "");
var maxWord = ed.settings.max_word;
var limited = "";
var content = ed.getContent();
if (writtenWords >= maxWord) {
$('.mce-wordcount').css("color", "red");
limited = $.trim(content).split(" ", maxWord);
limited = limited.join(" ");
ed.setContent(limited);
} else {
$('.mce-wordcount').css("color", "green");
}
});
}
});
Your solution lies here
https://github./AdamScheller/charwordcount
Ok Here is the plete solution.
Download the Zip File From the above Link. It is given in the right side bottom
Extract the zip folder in the plugins directory which is inside tinymce. So now you shoyld have a directory in your plugins directory named (charwordcount-master)
Then
just call the plugin in your code where you are initializing the editor. I am writing the whole head section here
<head>
<meta charset="utf-8">
<title>charwordcount TinyMCE plugin example</title>
<script src="tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
selector: "textarea",
plugins: [
"charwordcount advlist link image lists preview pagebreak",
"searchreplace code insertdatetime nonbreaking",
"table textcolor paste textcolor"
],
charwordcount_include_tags: false, // optional, includes HTML tags and entities (like ) in count; disabled by default;
toolbar1: "preview code | restoredraft undo redo | cut copy paste searchreplace | link unlink image | table | subscript superscript | nonbreaking | outdent indent blockquote | bullist numlist",
toolbar2: "formatselect fontselect fontsizeselect | bold italic underline strikethrough | forecolor backcolor | alignleft aligncenter alignright alignjustify",
menubar: false,
toolbar_items_size: 'small'
});
</script>
</head>
this is it now you have both the character and word count capability and it will show in the status bar of the editor. It will be applicable for every textarea.
I hope this makes it clear enough otherwise there is also an example in the zip folder it will be in the newly installed folder
\plugins\charwordcount-master\charwordcount-master\example
if you have any problem just let me know. This solution will work 100% as I had spend lot of time looking for the solution.
Saurabh Gupta
if you are also faced this problem means required validation is not working when you are using tinymce html editor, so i have one solution, please follow it and i hope your problem solve, Check below code install package of tinymce jquery in your application with the use of nuget package create one model like this Model
[Required(ErrorMessage = "Please enter About Company")]
[Display(Name = "About Company : ")]
[UIHint("tinymce_jquery_full"), AllowHtml]
public string txtAboutCompany { get; set; }
CSHTML OR VIEW
<div class="divclass">
@Html.LabelFor(model => model.txtAboutCompany, new { @class = "required" })
@Html.EditorFor(model => model.txtAboutCompany)
<span class="field-validation-error" id="AC" style="margin:9px 0 0 57px;">/span>
</div>
And this is jquery
$("#BusinessProfile").click(function () {
var aboutC = $("#txtAboutCompany").val()
var pinfo = $("#txtProductinfo").val();
if (aboutC == "" && pinfo == "") {
$("#AC").append("").val("").html("Please enter about pany")
$("#PI").append("").val("").html("Please enter product information")
$("#bpform").valid();
return false;
} else if (aboutC == "") {
$("#PI").append("").val("").html("")
$("#AC").append("").val("").html("Please enter about pany")
$("#txtAboutCompany").focus();
$("#bpform").valid();
return false;
} else if (pinfo == "") {
$("#AC").append("").val("").html("")
$("#PI").append("").val("").html("Please enter product information")
$("#txtProductinfo").focus();
$("#bpform").valid();
return false;
}
else {
$("#AC").append("").val("").html("");
$("#PI").append("").val("").html("");
//return true;
$("#bpform").validate();
}
});