count number of misspelled words - javascript

I have a project where I need to count the number of misspelled words in a text area and prevent submission of the web form if there are too many misspellings. The JavaScript editor, tinyMCE is used for the entry form. A PHP script, spellcheckText.php, counts the misspellings, if any, and returns a JSON encoded result back to the brows. Code example below:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" src="/simages/css/bootstrap/3.3.7/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="/simages/scripts/js/tinymce/js/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
selector: ".standard-editor",
plugins: "wordcount spellchecker",
paste_as_text: false,
theme: "modern",
branding: false,
content_style: ".mce-content-body {font-size:16px;font-family:Arial,sans-serif;}",
browser_spellcheck: true,
toolbar: "undo redo",
spellchecker_rpc_url: '/simages/spellchecker/spellchecker.php',
menubar: "tools",
statusbar: true,
height: "400",
width: "600",
paste_data_images: false,
paste_enable_default_filters: false,
paste_preprocess: function(plugin, args) {
args.content = '';
}
});
</script>
<script type="text/javascript">
function checkWordCount() {
var wordCount = tinyMCE.activeEditor.plugins["wordcount"].getCount();
if (wordCount < 50) {
alert("Need 50 words or greater for your text submission...");
return false;
}
var essayContent = tinyMCE.activeEditor.getContent({format: 'text'});
function getSpellCount(essayContent){
return new Promise((resolve,reject) => {
jQuery(function(\$) {
var values = { 'str': essayContent };
\$.ajax({
type: "POST",
url: "/path/to/spellcheckEssay.php",
data: values,
success: resolve,
error: reject,
})
});
})
}
var percentage = getSpellCount(essayContent);
percentage.then(function(result){
console.log(result);
var grade = result.percentage;
if(grade < 80){
alert("Please edit your response.");
return false;
}else{
document.essayform.submit();
}
}).catch(function (error) {
console.log('Failed',error);
});
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="form-group">
<form method=POST action="/path/to/ajax/textWords.php" name="essayform" id="essayQuestion" onsubmit="event.preventDefault();checkWordCount();">
<h3>$thesequestions{'Text'}</h3>
<p>
<textarea name="textarea" class="standard-editor" id="essay"></textarea>
</p>
<br/>
<input class="btn btn-primary" type="submit" value="Submit Text"/>
</form>
</div>
</div>
</body>
</html>```
I don't do front end coding that often, so don't know if the attempt to post twice in the same form is the problem or something else. Results of this example is a blank page where form's post action is executed. Don't believe that jQuery section is executed.
Open to suggestions for a better method.
Thank you.
**Below is a revision of the original code post**:
```<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" src="/css/bootstrap/3.3.7/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="/scripts/js/tinymce/js/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
selector: ".standard-editor",
plugins: "wordcount spellchecker",
paste_as_text: false,
theme: "modern",
branding: false,
content_style: ".mce-content-body {font-size:16px;font-family:Arial,sans-serif;}",
browser_spellcheck: true,
toolbar: "undo redo",
spellchecker_rpc_url: '/simages/spellchecker/spellchecker.php',
menubar: "tools",
statusbar: true,
height: "400",
width: "600",
paste_data_images: false,
paste_enable_default_filters: false,
paste_preprocess: function(plugin, args) {
args.content = '';
}
});
</script>
<script type="text/javascript">
function checkWordCount() {
var wordCount = tinyMCE.activeEditor.plugins["wordcount"].getCount();
if (wordCount < 50) {
alert("Need 50 words or greater for your text submission...");
return false;
}
var essayContent = tinyMCE.activeEditor.getContent({format: 'text'});
function getSpellCount(essayContent){
return new Promise((resolve,reject) => {
jQuery(function($) {
var values = { 'str': essayContent };
console.log(values);
$.ajax({
type: "POST",
url: "/path/to/ajax/spellcheckText.php",
data: values,
success: resolve,
error: reject,
})
});
})
}
var percentage = getSpellCount(essayContent);
percentage.then(function(result){
console.log(result);
var grade = result.percentage;
if(grade < 80){
alert("A number of misspelled words were detected. Please correct and submit again.");
return false;
}
}).catch(function (error) {
console.log('Failed',error);
});
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="form-group">
<form method=POST action="/path/to/ajax/textWords.php" name="essayform" id="essayQuestion" onsubmit="event.preventDefault();checkWordCount();">
<h3>$thesequestions{'Text'}</h3>
<p>
<textarea name="textarea" class="standard-editor" id="essay"></textarea>
</p>
<br/>
<input class="btn btn-primary" type="submit" value="Submit Text"/>
</form>
</div>
</div>
</body>
</html>```

Below is the revised code. The path to the solution was pointed out by Taplar where I was returning false incorrectly. Also accessing the tinyMCE data correctly helps make things work.
```<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" src="/simages/css/bootstrap/3.3.7/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="/scripts/js/tinymce/js/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
selector: ".standard-editor",
plugins: "wordcount spellchecker",
paste_as_text: false,
theme: "modern",
branding: false,
content_style: ".mce-content-body {font-size:16px;font-family:Arial,sans-serif;}",
browser_spellcheck: true,
toolbar: "undo redo",
spellchecker_rpc_url: '/path/to/spellchecker/spellchecker.php',
menubar: "tools",
statusbar: true,
height: "400",
width: "600",
paste_data_images: false,
paste_enable_default_filters: false,
paste_preprocess: function(plugin, args) {
args.content = '';
}
});
</script>
<script type="text/javascript">
function checkWordCount() {
var wordCount = tinyMCE.activeEditor.plugins["wordcount"].getCount();
if (wordCount < 50) {
alert("Need 50 words or greater for your text submission...");
return false;
}
var essayContent = tinyMCE.activeEditor.getContent({format: 'text'});
function getSpellCount(essayContent){
return new Promise((resolve,reject) => {
jQuery(function($) {
var values = { 'str': essayContent };
console.log(values);
$.ajax({
type: "POST",
url: "/path/to/ajax/spellcheckText.php",
data: values,
success: resolve,
error: reject,
})
});
})
}
var percentage = getSpellCount(essayContent);
percentage.then(function(result){
console.log(result);
var grade = result.percentage;
if(grade < 80){
alert("A number of misspelled words were detected. Please correct and submit again.");
return false;
}
}).catch(function (error) {
console.log('Failed',error);
});
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="form-group">
<form method=POST action="/path/to/ajax/textWords.php" name="essayform" id="essayQuestion" onsubmit="event.preventDefault();checkWordCount();">
<h3>$thesequestions{'text'}</h3>
<p>
<textarea name="textarea" class="standard-editor" id="essay"></textarea>
</p>
<br/>
<input class="btn btn-primary" type="submit" value="Submit Text"/>
</form>
</div>
</div>
</body>
</html>```

Related

Why this basic VEXFLOW code is rendering nothing?

I have a piece of code in VEXFLOW
<!DOCTYPE html>
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://unpkg.com/vexflow/releases/vexflow-min.js"></script>
<script>
$(function() {
import Vex from 'vexflow';
const vf = new Vex.Flow.Factory({
renderer: {elementId: 'boo', width: 500, height: 200}
});
const score = vf.EasyScore();
const system = vf.System();
system.addStave({
voices: [
score.voice(score.notes('C#5/q, B4, A4, G#4', {stem: 'up'})),
score.voice(score.notes('C#4/h, C#4', {stem: 'down'}))
]
}).addClef('treble').addTimeSignature('4/4');
vf.draw();
});
</script>
</head>
<body>
<div id="boo"></div>
</body></html>
Why this code is not rendering nothing.
Nothing is visible in browser.
<!DOCTYPE html>
<html>
<body>
<div id="boo"></div>
</body>
</html>
<script src="https://unpkg.com/vexflow/releases/vexflow-min.js"></script>
<script>
const vf = new Vex.Flow.Factory({
renderer: { elementId: "boo", width: 500, height: 200 }
});
const score = vf.EasyScore();
const system = vf.System();
system
.addStave({
voices: [
score.voice(score.notes("C#5/q, B4, A4, G#4", { stem: "up" })),
score.voice(score.notes("C#4/h, C#4", { stem: "down" }))
]
})
.addClef("treble")
.addTimeSignature("4/4");
vf.draw();
</script>

How to update a tree without refreshing whole page?

I'm creating web application with zTree.
The tree is built based on data from the Golang backend.
Tree leaves change custom icons while the application is running.
How to change icons, based on backend data, without refreshing the page?
With http-equiv="refresh" page is blinking and lost focus. Here is working but blinking sample with zTree and refresh (I cut of backend part for simplicity):
<HTML>
<HEAD>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh" content="5">
<link rel="stylesheet" href="../static/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="../static/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="../static/js/jquery.ztree.core.js"></script>
</HEAD>
<BODY>
<div id="app">
<TABLE>
<TR>
<TD width=260px valign=top>
<ul id="tree" class="ztree"></ul>
</TD>
<TD valign=top>
<p>Some text</p>
</TD>
</TR>
</TABLE>
<SCRIPT type="text/javascript">
var zTree;
var setting = {
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: ""
}
}
};
var zNodes = [
{id: 1, pId: 0, name: "root", icon:"../static/css/zTreeStyle/img/diy/c16green.png"},
{id: 2, pId: 1, name: "leaf", icon:"../static/css/zTreeStyle/img/diy/c16red.png"},
];
$(document).ready(function () {
var t = $("#tree");
t = $.fn.zTree.init(t, setting, zNodes);
});
</script>
</div>
</BODY>
</HTML>
I try to use Vue.js, but cannot bind data to zTree. Here is not working sample with Vue.js data binding inside script tag:
<HTML>
<HEAD>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../static/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="../static/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="../static/js/jquery.ztree.core.js"></script>
<script src="https://unpkg.com/vue"></script>
</HEAD>
<BODY>
<div id="app">
<TABLE>
<TR>
<TD width=260px valign=top>
<ul id="tree" class="ztree"></ul>
</TD>
<TD valign=top>
<p>{{ now }}</p>
<p>Some text</p>
</TD>
</TR>
</TABLE>
<SCRIPT type="text/javascript">
var zTree;
var setting = {
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: ""
}
}
};
var zNodes = [
{id: 1, pId: 0, name: "root", icon:"../static/css/zTreeStyle/img/diy/c16green.png"},
{id: 2, pId: 1, name: "leaf", icon:"../static/css/zTreeStyle/img/diy/c16red.png"},
{id: 3, pId: 1, name: "foo", icon: {{ customIcon }} },
];
$(document).ready(function () {
var t = $("#tree");
t = $.fn.zTree.init(t, setting, zNodes);
});
const app = new Vue({
el: '#app',
data: {
now: new Date(),
customIcon : "../static/css/zTreeStyle/img/diy/c16green.png"
},
methods: {
updateDate() {
this.now = new Date();
}
},
mounted() {
setInterval(() => {
this.updateDate();
}, 1000);
},
})
</script>
</div>
</BODY>
</HTML>
Zipped sample (examples are inside template directory): https://drive.google.com/file/d/1Ihv8jLdsEz93aUrFjEugD1l6YvslaUT8
The solution contains a few steps:
use "go-echo-vue" for communication between backend and frontend like here: https://github.com/covrom/go-echo-vue
update zTree data using vue-resource and timer like this:
<script>
new Vue({
// ....
methods: {
updateZNodes() {
// запрашиваем дерево :)
this.$http.get('/znodes').then(function (response) {
zNodes = response.data.items ? response.data.items : []
}, function (error) {
console.log(error)
});
},
},
mounted() {
setInterval(() => {
this.updateZNodes();
}, 5000);
},
// ....
})</script>
refrest zTree nodes information using js:
<script language="JavaScript">
function refreshNode() {
var treeObj = $.fn.zTree.getZTreeObj("tree");
var nodes = treeObj.getNodes();
if (nodes.length > 0) {
for (let i = 0; i < nodes.length; i++) {
c = "static/css/zTreeStyle/img/diy/c16grey.png";
if (zNodes.length >= i) {
c = zNodes[i].icon
}
nodes[i].icon = c;
treeObj.updateNode(nodes[i]);
}
}
};
const timerId = setInterval(
() => {
refreshNode();
},
5000
);
</script>
add async zTree settings:
<script language="JavaScript">
var setting = {
// ....
async: {
enable: true,
url: "",
autoparam: ["id", "icon"],
datatype: "json",
},
// ....
};
</script>
That's all. So we have Vue function http.get to get fresh data from backend, global js variable to use that data both inside Vue code segment and JavaScript blocks.
PS additional information: https://www.tutorialfor.com/blog-188266.htm

File_get_contents and echo with javascript

I'm not familiar with js. I'd like to get the result of "file_get_contents" function and put it on the "source" (I have marked both with "https://.................).
Thank you in advance.
<script>
var myInit = {
referrer: '',
};
function file_get_contents(filename) {
fetch(filename, myInit).then((resp) => resp.text()).then(function(data) {
content = JSON.parse(data)
fetch(content['some']['media']['content'], myInit).then((resp) =>
resp.text()).then(function(data));});}
file_get_contents("https://.................");
</script>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/clappr#latest/dist/clappr.min.js">
</script>
</head>
<div id="player"></div>
<script>
window.onload = function() {
var player = new Clappr.Player({
source: 'http://......................',
parentId: "#player",
height: '100%',
width: '100%',
autoPlay: true,
});};
</script>
</body>
</html>

Create javascript function for submit button to return data

I'm creating a blog on laravel and so far I have the successful js code for posts that contain a title and content. But I'm having some trouble writing the js function for tags.
I would like to do the same for tags but I'm getting errors on everything I try.
<script src="https://cloud.tinymce.com/stable/tinymce.min.js?apiKey=fg5tc8gb4rtw6p9n3njd2hi4965rketxda84pbcfs09hb5x2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.4/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: '.myeditablediv',
plugins: 'code , save, autoresize , textcolor colorpicker , emoticons, textpattern , wordcount',
toolbar: 'save , restoredraft , forecolor backcolor, emoticons',
save_onsavecallback: function () {
var content = tinymce.activeEditor.getContent();
console.log(content);
}
});
$(document).on('click', '#SubmitBtn', function () {
var content = tinymce.activeEditor.getContent();
var data = {
'title': $('#title').val(),
'content': content,
'_token': '{{csrf_token()}}'
};
$.post('/postData', data, function () {
console.log(data);
});
});
</script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Create the title</h1>
<form>
{{csrf_field()}}
<label for="title">Click here to edit the title of your post!</label>
<input type="text" name="title" id="title"/>
<h1>Create the content</h1>
<div class="myeditablediv">Click here to edit the content of your post!</div>
</form>
<input type="button" name="Submit" id="SubmitBtn" value="Submit"/>
</body>
</html>
<script src="https://cloud.tinymce.com/stable/tinymce.min.js?apiKey=fg5tc8gb4rtw6p9n3njd2hi4965rketxda84pbcfs09hb5x2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.4/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: '.myeditabletag', // change this value according to your HTML
menu: {
view: {title: 'Edit', items: 'cut, copy, paste'}
},
save_onsavecallback: function () {
var content = tinymce.activeEditor.getContent();
console.log(content);
}
});
$(document).on('click', '#SubmitBtn', function () {
var name = tinymce.activeEditor.getContent();
var data = {
'name': name,
'_token': '{{csrf_token()}}'
};
$.post('/postTags', data, function () {
console.log(data);
});
});
</script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Create a new Tag</h1>
<form>
{{csrf_field()}}
{{--<input type="text" name="name" id="name"/>--}}
<div class="myeditabletag">Click here to edit the name of your tag!</div>
</form>
<input type="button" name="Submit" id="SubmitBtn" value="Submit"/>
</body>
</html>
Here is the route for /postData for tags and posts:
Route::post('/postTags', ['uses' => 'TagController#store']);
Route::post('/postData', ['uses' => 'PostController#store']);
And here is the PostController and TagController store method:
public function store(Request $request)
{
$post = new Post;
$post->title = $request['title'];
$post->content = $request['content'];
$post->save();
}
public function store(Request $request)
{
$tag = new Tag;
$tag->name = $request['name'];
$tag->save();
}
You have a mistake in your JS code. You are selecting an ID that doesn't exist. You need to select the content of the changed tag, and send that as the data['name']. Try the following code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.4/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: '.myeditabletag', // change this value according to your HTML
menu: {
view: {title: 'Edit', items: 'cut, copy, paste'}
},
save_onsavecallback: function () {
var content = tinymce.activeEditor.getContent();
console.log(content);
}
});
$(document).on('click', '#SubmitBtn', function () {
var name = tinymce.activeEditor.getContent();
var data = {
'name': name,
'_token': '{{csrf_token()}}'
};
console.log(data);
$.post('/postTags', data, function () {
});
});
</script>

Adjusting Datepicker

I have small knowledge of JS, but I was assigned a task to add some functionality to page. I need to add a datepicker in birthDate field, but once I add datepicker function to page my, validation(Jquery validation) stop working.
Here is code:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page session="false"%>
<%# taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site- demos.css" />
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<title>Parent Registration</title>
</head>
<body>
<!-- Everything inside should be the body -->
<tiles:insertDefinition name="defaultTemplate">
<tiles:putAttribute name="body">
....some code.........
<div class="form-group" >
<label for="birthDate" class="col-sm-3 control-label">Birthday</label>
<div class="col-sm-6">
<form:input type="text" class="form-control float_left" id="birthDate" name="birthDate" path="birthDate" placeholder="MM/DD/YYYY" required="true" />
</div>
</div>
...........some code...........
<script src="/resources/js/jquery.validate.min.js"></script>
<script src="/resources/js/validation.js"></script>
<script>
jQuery.validator.addMethod(
"dateUS",
function(value, element) {
var check = false;
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if( re.test(value)){
var adata = value.split('/');
var mm = parseInt(adata[0],10);
var dd = parseInt(adata[1],10);
var yyyy = parseInt(adata[2],10);
var xdata = new Date(yyyy,mm-1,dd);
var currentTime = new Date();
var year = currentTime.getFullYear();
if ( ( xdata.getFullYear() == yyyy) && ( xdata.getFullYear() <= year ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == dd ) )
check = true;
else
check = false;
} else
check = false;
return this.optional(element) || check;
},
"Please enter a date in the format MM/DD/YYYY"
);
jQuery.validator.addMethod("parentName", function(value, element) {
return this.optional( element ) || /^(?=.*[a-zA-Z])([a-zA-Z.'-\s]+)$/.test( value );
}, 'The name should contain at least one alphabet character, space, dot, hyphen, apostrophe.');
$(document).ready(function(){
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#myform").validate({
rules: {
firstName: {
required: true,
parentName: true
},
middleName: {
parentName: true
},
lastName: {
required: true,
parentName: true
},
noOfChildren: {
required: true,
digits: true
},
birthDate: {
required: true,
dateUS: true
},
email: {
required: true,
email:true
},
confirmemail: {
required: true,
equalTo: "#email"
},
confirmpassword: {
required: true,
equalTo: "#password"
}
},
errorPlacement: function (label, element) {
if(element.is("input:checkbox")) {
element.parent("label").after( label );
} else if(element.is("input:radio")){
element.parent("label" ).parent("div:first").after( label );
}
else {
label.insertAfter( element );
}
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#birthDate" ).datepicker();
});
</script>
</tiles:putAttribute>
</tiles:insertDefinition>
</body>
</html>
You are including jquery 1.10.2 (at the bottom) and 1.11.3 (top) javascript files. This is most likely the problem.
Tipp: In Firefox you can debug your javascript and see error messages by pressing Ctrl+Shift+K or through Extras->Web-Developer->Web-Console.

Categories