Javascript not displaying unicode - javascript

I am using Javascript to display headers on a SharePoint site, according to a column that I have specified HTML in. Here is the HTML.
<DIV style ='text-align:center; font-weight:bold; font-size: 20px;'>◆</DIV>
The problem is that the script, while rendering the HTML properly within the page, does not do the same for header. It works 90% of the way, but instead of displaying the unicode "◆", it renders "â".
I've already tried modifying the Javascript to try to account for the unicode \u25c6, but I'm failing miserably. Can anyone help me out or provide me some clues as to why this is happening?
Here is the Javascript.
<script type="text/javascript">
// Find all Web Parts in the page
var listWP = [],
calWP = [],
divs = document.getElementById("MSO_ContentTable").getElementsByTagName("div");
var count=divs.length;
for (i=0;i<count;i++) {
try {
if (divs[i].id.indexOf("WebPartWPQ")==0){
if (divs[i].innerHTML.indexOf("ViewDefault_CalendarView")>=0) {
// Calendars
calWP.push(divs[i].id);
} else {
// Other Web Parts
listWP.push(divs[i].id);
}
}
}
catch(e){}
}
function TextToHTML(NodeSet, HTMLregexp) {
var CellContent = "";
var i=0;
while (i < NodeSet.length){
try {
CellContent = NodeSet[i].innerText || NodeSet[i].textContent;
if (HTMLregexp.test(CellContent)) {
NodeSet[i].innerHTML = CellContent;
}
}
catch(err){}
i=i+1;
}
}
var regexpA = new RegExp("\\s*<([a-zA-Z]*)(.|\\s)*/\\1?>\\s*$");
var regexpTD = new RegExp("^\\s*<([a-zA-Z]*)(.|\\s)*/\\1?>\\s*$");
var WP = new Object;
function UpdateWP() {
if (calWP.length>0){
for (i=0;i<calWP.length;i++) {
WP=document.getElementById(calWP[i]);
if (WP.innerHTML.indexOf("&lt\;")>=0) {
TextToHTML(WP.getElementsByTagName ("a"),regexpA);
}
}
}
if (listWP.length>0){
for (i=0;i<listWP.length;i++) {
WP=document.getElementById(listWP[i]);
if (WP.innerHTML.indexOf("&lt\;")>=0) {
TextToHTML(WP.getElementsByTagName ("td"),regexpTD);
}
}
}
// Check every 200000000 ms, forever
setTimeout("UpdateWP()",200000000);
}
UpdateWP();
function HeaderToHTML(){
var headers=document.getElementById("MSO_ContentTable").getElementsByTagName("li");
var regexpTR1 = new RegExp("FilterValue1=([\\S\\s]*)'\\)");
var regexpTR2 = new RegExp("FilterValue2=([\\S\\s]*)'\\)");
for (i=0;i<headers.length;i++) {
try{
var sp=headers[i].getElementsByTagName("span");
for (j=0;j<sp.length;j++) {
var test = sp[j].innerText || sp[j].textContent || " ";
//var test = sp[j].innerText;
if (test.indexOf("...")>0) {
//alert(test);
//var value = regexpTR1.exec(headers[i].innerHTML)[1];
var inner = headers[i].innerHTML;
var value = (inner.indexOf("FilterValue2")>0) ? regexpTR2.exec(headers[i].innerHTML) [1] : regexpTR1.exec(headers[i].innerHTML)[1];
//alert(value);
//alert(value.replace(/\\u00/g,"\%"));
value=value.replace(/\\u00/g,"%");
sp[j].innerHTML=unescape(unescape(value)).replace(/8_/," ");
}
}
}catch(e){}
}
}
setInterval(function(){HeaderToHTML();},100);
</script>

I would suggest using the html dex/dec for the symbols.
that is,
◆ = ◆
◆ = ◆
Wikipedia has a nice list of them broken into categories here.
I found the black diamond you're trying to write here

I think a solution could be to render your character in its encoding and let browser know about it via:
<meta http-equiv="Content-Type" content="text/html; charset="...">
For example, if you are using UTF-8:
<meta http-equiv="Content-Type" content="text/html; charset="UTF-8">

Related

"jQuery requires a window with a document" on jquery $get

Why does this error happen when it try to use jquery? This code was working before but I don't even know what did I do for this error to happen. I tried to search about it and nothing I looked up makes sense or it's about this jsdom or whatever that I don't use. Exception is thrown on the 1st line in the try catch. That's the only error I could get from the browser debugger:
function DisplayName() {
if (Page_ClientValidate()) {
try {
$get("lblNameShow").html = $get("<%= txtNome.ClientID %>").value;
$get("lblDataAdmissaoShow").innerHTML = document.getElementById("datepicker").value;
var ddlD = document.getElementById("<%= ddlDepartamento.ClientID%>");
var strDDLDepart = ddlD.options[ddlD.selectedIndex].text;
$get("lblDepartamentoShow").innerHTML = strDDLDepart;
var ddlF = document.getElementById("<%= ddlFuncao.ClientID%>");
var strDDLFunc = ddlF.options[ddlF.selectedIndex].text;
$get("lblFuncaoShow").innerHTML = strDDLFunc;
//get valor radio button
var rstTel = $('#<%=rblTelemovel.ClientID %> input[type=radio]:checked').val();
if (rstTel == 0)
$get("lblTelemovelShow").innerHTML = "Não"
else
$get("lblTelemovelShow").innerHTML = "Sim"
var message = "";
var checkBoxList = document.getElementById("<%=cblAppAlternativas.ClientID%>");
var checkBoxes = checkBoxList.getElementsByTagName("INPUT");
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var value = checkBoxes[i].value;
var text = checkBoxes[i].parentNode.getElementsByTagName("LABEL")[0].innerHTML;
message += value + "-" + text + ",";
}
}
//alert(message);
$get("lblAcessoShow").innerHTML = message;
$get("lblObShow").innerHTML = $get("<%= txtObservacoes.ClientID %>").value;
} catch (err) {
$get("demo").innerHTML = err.message;
}
$('#NewColabModal').modal('show')
}
return false;
}
EDIT
The code works if I remove the get from the jquery selector, but the strange thing is the code was working before. I can't find any info about using $get in jquery to select elements so I'm not sure about it if it's a plugin. This code was already implemented in the project I'm working on so I have no idea which plugin uses $get.
on the original project these are the only references on it
<link rel="stylesheet" type="text/css" href="jquery-ui-1.12.1.custom/jquery-ui.css" />
<script src="jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script>
<script src="jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script type="text/javascript" src="NOTY/js/noty/packaged/jquery.noty.packaged.js"></script>
EDIT 2
So I was using a try catch to catch the error but I was doing it in the wrong way since I'm still new to javascript. The exception I got is that $get is not defined. So rather than asking where $get comes from, how do I define a variable in jquery like $get?

Can't compare database query from flask to javascript variable

I have a flask-based site and I query the database in Flask and send that list of values to my html page. From there I have a script that compares a variable to an element in the list, but the case never works.
def start():
title = ""
paragraph = ["Cognitive Motor"]
pageType = 'start'
#if request.form.get("cognitiveAbility1" != None):
methodsQuery = db.engine.execute("select method from permutations")
motorQuery = db.engine.execute("select cognitivemotor from permutations")
motorList = motorQuery.fetchall()
data = request.stream.read()
methodList = methodsQuery.fetchall()
data2 = request.stream.read()
return render_template("start.html", title=title, paragraph=paragraph, pageType=pageType,data=data, methodList=methodList,motorList=motorList)
That is the code in flask, and below is the script I have in my html file.
The case if the if statement never works and won't print out the console.log("test").
<script>
$(document).ready(function() {
$(document).on('click', '.submitButton', function cognitiveFunction() {
var checkCog = document.getElementsByName("cognitive");
var checkMot = document.getElementsByName("motorCheck");
var resultCog = '';
var resultMot = '';
var motorQuery= "";
for(i = 0; i <3; i++) {
if(checkCog[i].checked === true) {
resultCog += checkCog[i].value + '';
console.log(resultCog);
}
}
for(i = 0; i <8; i++) {
if(checkMot[i].checked === true) {
resultMot += 'Yes';
}
else {
resultMot += 'No';
}
}
motorQuery = resultCog + resultMot ;
for(i = 0; i <19; i++) {
if ( '{{ motorList [i]}}' == motorQuery){
console.log('test');
$('body').append("{{ methodList [i] }}")
}
}
When I just print a value from the list of motorList into my html page manually, it looks like this,
(u'Cognitively intactNoNoYesNoYesNoYesYes',)
But in the database it is just
Cognitively intactNoNoYesNoYesNoYesYes
You have a basic misunderstanding of how JS and Flask interact. There is no possible way to put the JS variable i into the Jinja template variable '{{ motorList[i] }}, because Jinja is rendered on the server long before the JS runs on the client.
You will need to output the entire motorList in a format accessible to your script, ie JSON, and then iterate through that in JS.

How can i get value of text area?

i have two files
1)index.php
and
2)code.js
now code in index.php is below
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<link href="http://web.guru99.com/lib/codemirror.css" rel="stylesheet" />
<script type="text/javascript" src="code.js"></script>
<style type="text/css">
.CodeMirror {
border: 1px solid #eee;
height: auto;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
</head>
<body>
Integer : whole numbers e.g. -3, 0, 69. The maximum value of an integer is platform-dependent. On a 32 bit machine, its usually around 2 billion. 64 bit machines usually have larger values. The constant PHP_INT_MAX is used to determine the maximum value.
<pre class="codeguru">say 'hi';</pre>
Let us now look at how PHP determines the data type depending on the attributes of the supplied data.
<pre class="codeguru">say 'hello';</pre>
Floating point numbers
<pre class="codeguru">say 'you r amazing';</pre>
Character strings
<pre class="codeguru">say 'i am fine';</pre>
</div>
<form class="hidden code-box" method="GET" name="sample">
<div dir="ltr"><textarea class="php" name="codeguru"></textarea></div>
<input type="submit" value="Run" onclick="execute();"/>
</br></br>
Output:</br></br>
<textarea id="print-result" disabled="true" cols="77"></textarea></br>
</form></div>
</body>
</html>
and code.js file contain code is given below
$(document).ready(function()
{
$('pre.codeguru').each(function()
{
var pre = this;
var form = $('form[name=sample]').clone();
$(form).removeAttr('name');
$(form).removeClass('hidden');
$($(form).find('textarea')[0]).val($(pre).text());
var id = $(pre).attr('id');
$(form).find('div textarea[name=code]').first().attr('id', id);
$(pre).replaceWith(form);
});
window.editors = [];
$('textarea[name=codeguru]').each(function()
{
window.editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
});
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = editor.getValue();
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('print-result').value = "";
try {
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
}
catch(err) {
//document.getElementById('log-result').value += "Error:\n";
}
}
everything is run fine in my code. in code.js pre tags are replaced by textarea and the code in textarea should be run because this project is of online perl editor. so now my problem is i have alert the value of text area by this code
var source = editor.getValue();
alert(source);
but that gives the blank pop up. so what i have to do for retrieve current value of textarea?
You have created more than one editor in this code. These seems to be stored in editors array. Now you want to execute execute() by clicking a button, but you're not telling JS, which editor value you want to alert.
The value of the first editor on the page can be reached like this:
var source = editors[0].getValue();
editor.getValue() is supposed to give you the value of the last editor in the editors array.
Since you have a separate button for each editor, you can pass the editor's index in the editors array to execute() function.
At first, remove the onclick attribute from the button input, then:
After $('pre.codeguru').each();, attach eventlisteners to buttons:
var n = 0;
$('input[type=button]').each(function () {
$(this).click(function (x) {
return function () {
execute(x);
};
}(n++))
}
);
And in the execute():
function execute(idx) {
...
var source = editors[idx].getValue();
alert(source);
....
}
UPDATE
Updated the fiddle code to output to a corresponding field.
And here is an updated live demo.

SQLite access in Javascript

I want to access Sql Lite Database with JavaScript code. The JavaScript code is used in html5 and has to be deployed on blackberry 10 platform.
I use the following code without success:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Prova</title>
</head>
<body>
<script type="text/javascript">
//Provenia SRL ITC - Paola Savioli
//Questa funzione apre il database SQL Lite
//Il parametro che va cambiato è il nome del database
function ApriDatabase() {
try {
if (window.openDatabase) {
var shortName = 'Ristoranti.sqllite';
var version = '1.0';
var displayName = 'Ristoranti italia';
var maxSize = 65536; // in bytes
db = openDatabase(shortName, version, displayName, maxSize);
}
} catch (e) {
alert('Apri Database' + e);
}
}
//Provenia SRL ITC - Paola Savioli
// Questa funzione eseque una query su un database aperto con la funzione ApriDatabase
function EseguiQuery($query, callback) {
try {
ApriDatabase();
if (window.openDatabase) {
db.transaction(
function (tx) {
tx.executeSql($query, [], function (tx, result) {
if (typeof (callback) == "function") {
callback(result);
} else {
if (callback != undefined) {
eval(callback + "(result)");
}
}
}, function (tx, error) {});
});
return rslt;
}
} catch (e) {
alert('Esegui Query' + e);
}
}
function VisualizzaComuni() {
try {
var schemanode = document.GetElementById('RCOMUNI');
schemanode.innerHTML = "";
var result = EseguiQuery('SELECT * FROM COMUNE');
for (var i = 0; i < result.rows.lenght; ++i) {
var row = result.row.item(i);
var notediv = document.createElement('div');
notediv.innerHTML = 'Codice Provincia:' + row['PROVINCIA'] + 'Nome:' + row['NAME'];
schemanode.appendchild(notediv);
}
} catch (e) {
alert('Visualizza Comuni' + e);
}
}
</script>
<input type="button" name='select' onClick="VisualizzaComuni()"
value='Visualizza Comuni'>
<div id="RCOMUNI"></div>
</body>
</html>
You may consider using the WebSQL API, which is supported on BlackBerry 7 and 10 according to http://caniuse.com/#feat=sql-storage.
Note that the API will never become an official standard and development on it has stopped. But if you just want to target BlackBerry, it may be a valid choice.
There were a few problems with the code you've posted, including a reference to .lenght instead of .length and use of try catch blocks when there are success and error handlers built-in. So I worked up a demo.
First, it does not seem to make a difference, but this is HTML5 right? Instead of an HTML 4.01 Transitional doctype, use the HTML5 doctype:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>demo by userdude</title>
...
Next, I modified the markup for the purposes of the demonstration. In this case, we have:
<body>
<input type="button" id="run" value='Run Query'>
<div id="query"></div>
<table id="table" border="1" cellspacing="1" cellpadding="5"></table>
</body>
</html>
In the head element, I use an event listener to wait for the DOM to load. Keep in mind, I do not have a Blackberry to test this with, and with Blackberry or other devices, you should probably use deviceready instead of load. I think. I also attach the event handler for button that run's the query using .addEventListener, but notice I do that within the load handler. You have to wait before trying to access the DOM.
Also, IE supports attachEvent instead of addEventListener. I would imagine Blackberry supports the latter, but I'm not sure.
window.addEventListener('load', function load(){
var run = document.getElementById('run'),
data = document.getElementById('table'),
qtext = document.getElementById('query'),
dropped = false,
created = false,
cities = ['Houston', 'Dallas', 'Paris', 'New York', 'Buenos Aires', 'London'],
shortName = 'Cities',
version = '1.0',
displayName = 'Cities Demo',
maxSize = 5 * 1024 * 1024,
db = false,
queries = [];
run.addEventListener('click', query);
This establishes my database, including running the initial call to populate() so we have some data use.
open();
This is the function I added to the run button.
function query() {
transact('SELECT * FROM Cities', view);
}
This is just meant to add data to the database. See the cities variable above.
function populate(tx) {
var city,
i = 0;
I block this from running once I've emptied the cities array of entries to INSERT. dropped and created do the same thing for the DROP and CREATE transactions.
Take special note how I'm doing this; see the transact('...', populate)? I use populate in this situation to loop back until I've finished adding all of the cities entries. This is asynchronous, so you have to setup the callbacks to wait if necessary for the previous queries to run. In this case, I could end up dropping the table after adding my rows. So I have to wait, then loop through the cities list.
if (cities) {
if (!dropped) {
dropped = true;
transact('DROP TABLE IF EXISTS Cities', populate);
return;
}
if (!created) {
created = true;
transact('CREATE TABLE IF NOT EXISTS Cities (id unique, City)', populate);
return;
}
I don't need to iterate back to populate here, since I just need to INSERT and move on.
while (city = cities.pop()) {
transact('INSERT INTO Cities (id, City) VALUES (' + i++ + ', "' + city + '")');
}
cities = false;
}
}
All this function does is give either an opened or new reference to the database, or return false. This short-circuits the execution of transact().
function open() {
if (!db && window.openDatabase) {
db = window.openDatabase(shortName, version, displayName, maxSize);
}
if (cities) {
db.transaction(populate);
}
return db;
}
This is the meat of the script. I call it from query(), and the callback in this case is view, which points to the function which runs through the result set and creates a table from the set.
function transact(query, callback) {
var cb = callback,
qel = document.createElement('p'),
qid = queries.length;
if (!open()) {
console.log('HTML5 Database not supported.');
return false;
}
db.transaction(transact_cb);
qel.innerHTML = query + ' Query Result: <span id="q' + qid + '">Pending...</span>';
qtext.appendChild(qel);
queries[qid] = query;
Note the last two arguments, transact_success, transact_error. This is how you handle these asynchronous calls.
function transact_cb(tx) {
tx.executeSql(query, [], transact_success, transact_error);
}
Not quite sure why there's an eval in there...?
function transact_success(tx, result) {
var rtext = document.getElementById('q' + qid);
rtext.className = 'success';
rtext.innerHTML = 'Success.';
if (typeof cb == "function") {
cb(result);
} else if (cb != undefined) {
eval(cb + "(result)");
}
}
Note the console.log(error);.
function transact_error(tx, error) {
var rtext = document.getElementById('q' + qid);
rtext.className = 'error';
rtext.innerHTML = 'Error logged to console.';
console.log(error);
}
}
And this function creates the table result set view. You'll probably notice I loop through each row, and each row's columns.
function view(result) {
var thead = '<thead><tr>',
tbody = '<tbody>',
row,
col;
for (var i = 0, rows = result.rows.length; i < rows; ++i) {
row = result.rows.item(i);
tbody += '<tr>';
for (col in row) {
if (i === 0) {
thead += "<th>" + col + "</th>";
}
tbody += '<td>' + row[col] + '</td>';
}
tbody += '</tr>';
}
thead += '</tr></thead>';
tbody += '</tbody>';
data.innerHTML = thead + tbody;
}
});
You can download the file and run it locally (due to a security error, it won't run on jsFiddle) by downloading the HTML file here:
http://pastebin.com/FcSiu6ZZ
So there you go. Hopefully that will help make this easier to understand. Let me know if you have any questions.

How do i solve these issues?

I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)

Categories