Prevent submitting a form - event-handling

I am making a DB of words. And before submitting a new word I want to check if entered word already exists in my DB. For that, I added e.preventDefault() but somehow it does not prevent the form and submitted with the same word that I already have (though the message is displayed correctly)
let bannedWords = <?php echo json_encode($bannedwords); ?>;
$('#submitAddedWord').submit(function (e) {
e.preventDefault();
for (let i = 0; i < bannedWords.length; i++) {
let word = document.querySelector('#word').value;
let message = document.createElement('p');
if(bannedWords[i].word === word) {
message.innerHTML = 'Oooops, this word already exists';
message.style.color = 'red';
document.querySelector('.form-group').append(message);
// setTimeout(function() {message.innerHTML = ''},1500);
} else {
$(this).unbind('submit').submit();
}
}
});`

Related

Is it necessary to create <span> elements to register event listeners

I have a working web app that reads local .txt files and displays the content in a div element. I create a span element out of each word because I need to be able to select any word in the document and create an EEI (Essential Elements of Information) from the text. I then register a click handler on the containing div and let the event bubble up. The three functions below show reading the file, and parsing it, and populating the text div with spans:
function readInputFile(evt) {
reset();
var theFile = evt.target.files[0];
if(theFile) {
$("#theDoc").empty(); //Clean up any old docs loaded
var myReader = new FileReader();
var ta = document.getElementById("theDoc");
myReader.onload = function(e) {
parseTheDoc(e.target.result);
initialMarkup();
};
myReader.readAsText(theFile);
} else {
alert("Can not read input file: readInputFile()");
}
}
function parseTheDoc(docContents) {
var lines = docContents.split("\n");
var sentWords =[];
for(var i = 0; i < lines.length; i++) {
sentWords = lines[i].split(" ");
words = words.concat(sentWords);
words.push("<br>");
}
//examineWords(words);
createSpans(words);
}
function createSpans() {
for (var i = 0; i < words.length; i++) {
var currentWord = words[i];
if(currentWord !== "<br>") {
var $mySpan = $("<span />");
$mySpan.text(currentWord + " ");
$mySpan.attr("id", "word_" + i);
$("#theDoc").append($mySpan);
buildDocVector(currentWord, i, $mySpan);
}
else {
var $myBreak = $("<br>");
$myBreak.attr("id", "word_" + i);
$("#theDoc").append($myBreak);
buildDocVector("br", i, $myBreak);
}
}
//console.log("CreateSpans: Debug");
}
So basically a simple fileReader, split on \n, then tokenize on white space. I then create a span for each word, and a br element for each \n. It's not beautiful, but it satisfies the requirement, and works. My question is, is there a more efficient way of doing this? It just seems expensive to create all these spans, but my requirement is to annotate the doc and map any selected word to a data model/ontology. I can't think of a way to allow the user to select any word, or combination of words (control click) and then perform operations on them. This works, but with large docs (100 pages) I start having performance/memory issues. I understand this is more a design question and may not be appropriate, but I'd really like to know if there are more performant solutions.

Word web addin load whole document from server header/footer

We are trying to load a word document from server using JavaScript. We send the document using a base64 encoding. With our current approach, only the body is loading using the function:
context.document.body.insertFileFromBase64(fileContent, "replace");
Unfortunately, the header and the footer are not loading. Is there another approach to load the whole document including body and footer?
the insertFile operation does not overwrite existing header/footers in the document.
According to my research, I saw this article for using insertFileFromBase64.The article says," if you use insertFileFromBase64 to insert the file it does have this blank page with header and footer." Did you have the same issue for this?
However, another article says it's a design issue. Userform will encode data and will create an appointment on Microsoft Outlook Calendar
The article provides approach:
function getFile(){
Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 4194304 /*64 KB*/ },
function (result) {
if (result.status == "succeeded") {
// If the getFileAsync call succeeded, then
// result.value will return a valid File Object.
var myFile = result.value;
var sliceCount = myFile.sliceCount;
var slicesReceived = 0, gotAllSlices = true, docdataSlices = [];
console.log("File size:" + myFile.size + " #Slices: " + sliceCount);
// Get the file slices.
getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
}
else {
app.showNotification("Error:", result.error.message);
}
});
}
function getSliceAsync(file, nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived) {
file.getSliceAsync(nextSlice, function (sliceResult) {
if (sliceResult.status == "succeeded") {
if (!gotAllSlices) { // Failed to get all slices, no need to continue.
return;
}
// Got one slice, store it in a temporary array.
// (Or you can do something else, such as
// send it to a third-party server.)
docdataSlices[sliceResult.value.index] = sliceResult.value.data;
if (++slicesReceived == sliceCount) {
// All slices have been received.
file.closeAsync();
onGotAllSlices(docdataSlices);
}
else {
getSliceAsync(file, ++nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
}
}
else {
gotAllSlices = false;
file.closeAsync();
console.log("getSliceAsync Error:", sliceResult.error.message);
}
});
}
function onGotAllSlices(docdataSlices) {
var docdata = [];
for (var i = 0; i < docdataSlices.length; i++) {
docdata = docdata.concat(docdataSlices[i]);
}
var fileContent = new String();
for (var j = 0; j < docdata.length; j++) {
fileContent += String.fromCharCode(docdata[j]);
}
var mybase64 = window.btoa(fileContent);
console.log("here is the base 64", mybase64);
// Now all the file content is stored in 'fileContent' variable,
// you can do something with it, such as print, fax...
}

Inserting current date into confluence hyperlink

I am using this code to display current date in the confluence page.
{run-now:dateFormat =d-MMM-yyyy}
$current_time
{run-now}
My purpose, to include this date into email hyperlink, like below
[Click me|mailto: some_email#domen.com &subject=Update as of - {run-now:dateFormat =d-MMM-yyyy} $current_time{run-now}]
My expectations, is that it will show mailto link after clicking which, it will open email with subject that is including current date.
But this is working unexpectedly
it shows me something like this instead of the link
function run_moreDisplayToggle_1() { // toggle display of "more" rows of parameter table on or of //alert("test"); var table = document.getElementById("run_table_1"); var rows = table.getElementsByTagName("tr"); var isMoreFound = false; for (var i = 0; i < rows.length; i++) { var row = rows.item(i); if (row.id.match("1_row_")) { if (row.style.display == "none") { row.style.display = ""; isMoreFound = true; } else { row.style.display = "none"; } } } var icon = document.getElementById("run_1_advanced_toggle"); var moreElement = document.getElementById("run_1__more") if (isMoreFound) { icon.src = "/images/icons/subtract_12.gif"; icon.title = "Less"; moreElement.value = "true"; } else { icon.src = "/images/icons/add_12.gif"; icon.title = "More"; moreElement.value = "false"; } }
29-Jan-2014" class="external-link" rel="nofollow">Click me
It's better you use HTML Macro to hyperlink your email.
I think it should be something like this:
{html}<a mailto: some_email#domen.com &subject=Update as of - {run-now:dateFormat =d-MMM-yyyy} $current_time{run-now}/a>{html}
Anyway as the confluence expertise always online in Answers I recommend you to check there.

recall form value not working for textareas

Im trying to modify this script
http://www.dynamicdrive.com/dynamicindex16/formremember2.htm
to work for textareas, and not just input text boxes. Heres what im guessing are the relevant parts of the script, i just cant figure it out myself
rememberForm.prototype.savevalues=function(){ //get form values and store in cookie
for (var i=0; i<this.fields.length; i++){
if (this.fields[i].type=="text")
this.cookiestr+=this.fields[i].fname+":"+escape(this.fields[i].value)+"#"
}
if (typeof this.togglebox!="undefined"){ //if "remember values checkbox" is defined
this.persistdays=(this.togglebox.checked)? this.persistdays : -1 //decide whether to save form values
this.cookiestr=(this.togglebox.checked)? this.cookiestr+"toggleboxid:on;" : this.cookiestr
}
else //if checkbox isn't defined, just remove final "#" from cookie string
this.cookiestr=this.cookiestr.substr(0, this.cookiestr.length-1)+";"
setCookie(this.cookiename, this.cookiestr, this.persistdays)
}
rememberForm.prototype.recallvalues=function(){ //populate form with saved values
var cookievalue=getCookie(this.cookiename)
if (cookievalue!=""){ //parse cookie, where cookie looks like: field1:value1#field2:value2...
var cookievaluepair=cookievalue.split("#")
for (var i=0; i<cookievaluepair.length; i++){
if (cookievaluepair[i].split(":")[0]!="toggleboxid" && this.getfield(cookievaluepair[i].split(":")[0]).type=="text")
this.getfield(cookievaluepair[i].split(":") [0]).value=unescape(cookievaluepair[i].split(":")[1])
else //else if name in name/value pair is "toggleboxid"
this.togglebox.checked=true
}
}
The method persistfields(id, ...) sets the fields you want to persist in the cookie. The fields are looked up by id so I guess adding a textarea with an id attribute would suffice.
For example:
<form id="myFormId">
<input type="text" id="someInputId" />
<textarea id="textareaId"></textarea>
</form>
<script>
var f = new rememberForm('myFormId');
f.persistfields('someInputId', 'textareaId');
</script>
This will add the input and textarea to the rememberForm instance fields property.
UPDATE
The problem lies in this method of rememberForm. I formatted the code for readability since the original source has horrible formatting.
rememberForm.prototype.savevalues = function() {
for (var i = 0; i < this.fields.length; i++) {
// PROBLEM: only allows type="text"
if (this.fields[i].type == "text") {
this.cookiestr += this.fields[i].fname + " : " + escape(this.fields[i].value) + "#"
}
if (typeof this.togglebox != "undefined") {
this.persistdays = (this.togglebox.checked) ? this.persistdays : -1;
this.cookiestr = (this.togglebox.checked) ? this.cookiestr + "toggleboxid:on;" : this.cookiestr
} else {
this.cookiestr = this.cookiestr.substr(0, this.cookiestr.length - 1) + ";"
setCookie(this.cookiename, this.cookiestr, this.persistdays)
}
}
}
As mentioned in my comment it will test the type of the input element to be 'text'. If you'd like to add textareas in the cookie you could change that line to:
if (this.fields[i].type == "text" || this.fields[i].type == 'textarea') {
That should work.

How to Delete Facebook Messages via Facebook API?

Is there a way to retrieve all Facebook Message ids with the read mailbox permission and then delete them all one by one? Everyone is crying about how it's difficult to delete your chat/message history. I wondered if there was an easy way to write an app to do this.
Facebook API - Message
Normally you would issue an HTTP DELETE call to https://graph.facebook.com/messageID?access_token=... But it appears that this is an API call that either require special whitelisting from Facebook or isn't currently supported because it does not work right now and returns "Unsupported delete request."
Install https://chrome.google.com/webstore/detail/jquerify/gbmifchmngifmadobkcpijhhldeeelkc
Open the facebook using
https://mbasic.facebook.com/messages/?_rdr
Enable jQuery using jQueryify extension you installed.
Then go to your chrome developer tools> sources > snippet and create a new snippet and paste the following code and run it.
// Code snippet for facebook messages removing:
var WHITELISTED_USERS_X = [];
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
if (element) {
element.parentNode.removeChild(element);
}
}
function addElement(parentId, elementTag, elementId, html) {
// Adds an element to the document
// removeElement
removeElement(elementId);
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
if (p) {
p.appendChild(newElement);
} else {
var body = document.getElementsByTagName("body")[0]
body.appendChild(newElement);
}
}
addElement("body", "div", "123x", "hello World23");
console.log(`getOlderMessagesLink()`);
console.log(getOlderMessagesLink());
var aLinks = document.querySelectorAll('h3 a'), i;
for (i = 0; i < aLinks.length; ++i) {
let currentLink = aLinks[i];
currentLink.style.color = currentLink.style.color == "black" ? "red" : "green";
$.get( currentLink.href, function( data ) {
getPayload1(currentLink.href).then(payLoad=>{
let abLink = currentLink.href;
let deleteApiLink = abLink.split('?').pop().split('&');
deleteApiLink.splice(1 , 0, `tids=${deleteApiLink[0].split('=').pop()}`)
deleteApiLink = deleteApiLink.join("&").split("#").shift();
const apiLink = `https://mbasic.facebook.com/messages/action_redirect?` + deleteApiLink;
$.post(apiLink, payLoad ).done(function( data ) {
let mydeletehref = findInParsed(data, "a:contains('Delete')");
const username = currentLink.innerText;
const deleteLink = mydeletehref.href;
if(WHITELISTED_USERS_X.indexOf(username) == -1){
// console.log(`${username}: ${deleteLink}`);
insertDeleteLinkInUser(username, deleteLink);
}
});
});
})
}
function getPayload1(link){
return new Promise(resp=>{
$.get(link, function( html1 ) {
let fbDtsg = findInParsed(html1, "input[name='fb_dtsg']");
let jazoest = findInParsed(html1, "input[name='jazoest']");
resp ({
"fb_dtsg": fbDtsg.value,
"jazoest": jazoest.value,
"delete": "Delete"
})
});
})
}
function findInParsed(html, selector){
return $(selector, html).get(0) || $(html).filter(selector).get(0);
}
function getOlderMessagesLink(html = false){
if(html){
return $("#see_older_threads").find("a").get(0).href;
}
let selector = "#see_older_threads";
return $(selector, html).find("a").get(0).href || $(html).filter(selector).find("a").get(0).href;
}
function insertDeleteLinkInUser(username, link){
$("a:contains('" + username + "')").parent().parent().parent().prepend('DELETE ME');
}