Write jQuery statement in plain JavaScript - javascript

I'm using the Wikipedia API to fetch just the first para of an article for which a keyword has been provided.
I have to extract formatted text from the JSON response but suppress some of the unwanted info like the sidebar (which is in a table & has the class name infobox) before I show it in a div whose id is wiki -
$.getJSON("http://en.wikipedia.org/w/api.php?" +
"action=mobileview&format=json&page=" +
keyword + "&redirect=no&sections=0&prop=text&" +
"sectionprop=toclevel%7Clevel%7Cline%7Cnumber" +
"%7Cindex%7Cfromtitle%7Canchor&callback=?",
function(json) {
$('#wiki').html(json.mobileview.sections[0].text)
.find("dl,sup,.thumb,table.infobox,table.metadata")
.remove().end();
}
);
I've adapted the jQuery trick to remove tags/selectors from the JSON response containing the HTML code of the requested Wikipedia page. I want to use the above snippet in a Windows 8 Store app written in HTML/JS. I wish to convert the following line to native JavaScript and implement the selector removal code without using jQuery -
$('#wiki').html(json.mobileview.sections[0].text)
.find("dl,sup,.thumb,table.infobox,table.metadata")
.remove().end();
I'm a JavaScript newbie. Can anyone please convert this line to plain-vanilla JavaScript?

var wiki = document.querySelector('#wiki');
wiki.innerHTML = json.mobileview.sections[0].text;
var content = wiki.querySelectorAll("dl,sup,.thumb,table.infobox,table.metadata");
for (var i = 0; i < content.length; i++) {
if (content[i].nodeName.toUpperCase() === "A")
content[i].parentNode.insertBefore(content[i].firstChild, content[i]);
content[i].parentNode.removeChild(content[i]);
}
This will work in most browsers including IE8 and higher.

Related

Reading embedded data into Qualtrics in a generalized way

I have a set of embedded variables, q1_ans, q2_ans, q3_ans, ....
In one of my questions, I would like to read in all these vars one at a time as part of a loop:
Qualtrics.SurveyEngine.addOnload(function()
{
var i;
for (i = 1; i <= 2; i++) {
let ans_q = "e://Field/q" + i + "_ans"
let ans = "${" + ans_q+ "}";
console.log(ans);
}
});
However, this is not reading in the embedded data values. How can I read in my embedded variables in a JS loop?
Embedded data fields are resolved on the server before the page is sent to the browser, so you can't dynamically build and resolve the pipe strings for embedded data fields in JavaScript.
You could pipe all the strings into an array definition, then loop through the array.
Another alternative would be to use Qualtrics.SurveyEngine.getEmbeddedData() if it still works (no longer included in documentation).

Convert javascript arrays into HTML table using DOM

I am currently creating a desktop app using tide sdk. All of my database information is stored into Parse.com (a serverless database). What I am trying to do is to take the array of the information I queried from Parse (in javascript) and insert it into a table. I am really having a hard time getting used to not using document.write() for my desktop application.
I want the end result to look like:
This is what I started with:
var contactNameArray = [];
var contactNumberArray= [];
var CM = Parse.Object.extend("ContactMenu");
var queryContact = new Parse.Query(CM);
queryContact.ascending("ContactName");
queryContact.find({
success: function(results4) {
alert("Successfully retrieved " + results4.length + " entries.");
// Do something with the returned Parse.Object values
// document.write('<table border="1" cellspacing="1" cellpadding="5">');
for (var i = 0; i < results4.length; i++) {
var object4 = results4[i];
contactNameArray[i] = object4.get('ContactName');
contactNumberArray[i] = object4.get('ContactNumber');
// document.write("<tr><td>Number " + i + " is:</td>");
//document.write("<td>" + contactNameArray[i] + "</td></tr>");
}
//document.write('</table>');
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
After doing some research I cam upon this bit of code from http://www.w3schools.com/jsref/dom_obj_table.asp which wrote: the correct response on the bottom of the left handed corner of the screen. (Kind of strange in my opinion). In code how can I better position this table to be in the center for my screen? Is there a way to center this table in javascript?
function generate_table() {
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.body.appendChild(x);
var y = document.createElement("TR");
y.setAttribute("id", "myTr");
document.getElementById("myTable").appendChild(y);
var z = document.createElement("TD");
for(var i = 0; i< query4.length; i++){
var t = document.createTextNode(contactNameArray[i]);
z.appendChild(t);
var m = document.createTextNode(contactNumberArray[i]);
z.appendChild(m);
}
document.getElementById("myTr").appendChild(z);
}
So I have already figured out how to put the information I want into an array. I am just having a hard time putting this information into a table that is correctly positioned. Thank you in advance. If you need to see any more of my code, then just let me know. If I am unclear, please let me know what I should explain. Thank you!!!
There are several ways to do this. But from what you already have the simplest is to use innerHTML:
queryContact.find({
success: function(results4) {
var html = "";
alert("Successfully retrieved " + results4.length + " entries.");
// Do something with the returned Parse.Object values
html += '<table border="1" cellspacing="1" cellpadding="5">';
for (var i = 0; i < results4.length; i++) {
var object4 = results4[i];
contactNameArray[i] = object4.get('ContactName');
contactNumberArray[i] = object4.get('ContactNumber');
html += "<tr><td>Number " + i + " is:</td>";
html += "<td>" + contactNameArray[i] + "</td></tr>";
}
html += '</table>';
document.body.innerHTML += html;
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
As for centering the table on the page the best way is to use CSS. Unfortunately centering anything in CSS is a bit of a hack. There are several ways to do it. See the answers to this question for all the ways of doing it: How to horizontally center a <div> in another <div>?. Note: scroll through the answers, not just read the top one. There really are a lot of ways to do this and some may not work for you.
A few notes about innerHTML:
Although innerHTML looks like a variable it actually behaves more like a function. Specifically it invokes the HTML compiler of the browser. So if you pass it incomplete tags like:
someDiv.innerHTML += '<table>';
it will see that as an incomplete 'table' tag and deals with it the way the browser usually does when it sees an incomplete 'table' tag. For some browsers that means removing the table from the DOM. For others that means immediately inserting a closing </table> tag to make it valid. What this means is that when you later append the closing tag like this:
someDiv.innerHTML += '</table>';
what happens is that the browser will think you did this:
<table></table></table>
^ ^
| |_________ what you're trying to insert
|
auto inserted by the browser earlier
and deal with it the way browsers usually do - consider that tag invalid and discard it.
So you need to pass innerHTML well-formed html which is why I created the table structure in a string then append it to the DOM with innerHTML.
A lot of people consider innerHTML stylistically bad since you're doing DOM manipulation with strings. Also because innerHTML was not originally part of any standard and was a proprietary feature of IE. Since it's not part of any standard there's no real agreement between different browsers for how it should work. Having said that, it's probably the most cross-bowser compatible method of manipulating DOM because it's the most widely implemented (even on really old browsers).
Read the documentation of the DOM API for more info on how to do it "properly": https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
As mentioned by others in the comment to your question, there are also libraries out there that would make your life easier for DOM manipulation. There are procedural libraries like jQuery that wraps the often clunky DOM API and cross-browser issues into a nice to use API. There are also templating library like handlebars that allows you to write the HTML fragments as templates to be processed and inserted into the DOM.
I suggest getting comfortable with how the DOM works by reading the DOM documentation and follow some tutorial and also look at DOM manipulation libraries like jQuery or YUI or underscore to get a better feel of javascript.
Paraphrasing Douglas Crockford, you wouldn't start to program in C or Java without learning the language first. Similarly javascript is a full-featured language. Take some time to learn it and not just assume that "it works like [insert a language you know]". There are many features of javascript like closures and asynchronous functions that will trip you up. Similarly the DOM has many behaviors that may work differently from your assumptions of how HTML works.
But it is a lot to take in. So for now use innerHTML with care being aware of its limitations. Also look at document.getElementById() which is the second most used DOM API for beginners. It allows you to insert your html anywhere in the document using innerHTML. Not just the end of the document.
From reading your questions I deduced the following...
How can I center my table using javascript.
I am having an issue getting my information into a table.
Typically it is not a good idea to do styling within your javascript. While it may seem nice to handle such things conveniently within your jscript, it can end up blowing up your code if not used with moderation. Your best bet would be to write some css, perhaps a generic class that can center an element to a page, and then apply this class to the table element. No Javascript needed, and it makes your code more modular to boot!
Here is a hacky bit of centering code that has worked for me to center a registration form div (Height and Width can be adjusted however you like, use of pixels is not a must.):
body > #register {
margin: auto;
position: absolute;
text-align: center;
height: 156px;
width: 160px;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
For the issues you are experiencing adding information to your table, without knowing what errors or exact output your are seeing, all I can do is go off what I can see in the code. Your generate table function has a few areas I noticed....
The function creates a table, sets an id to it, and appends it to the document, it then creates a new row, setting an id to it as well, it then appends the new row to the table. Then a cell is created.
Here is where I see a problem...
You then jump into a for loop limited by the length of query4 (I'll assume this is the query containing your contact info) and create text nodes, appending them to z (the cell) each iteration, if I am not mistaken that would actually result in the cell in the first(and only) row getting blown up with all your query info. What should be happening is the for loop adds the name and number to its own cells in a NEW row each iteration. This would be your psuedocode...
Create table
Start for loop over contact info for each item...
Create new row
Create new cells
add info to respective cells
append cells to row
append row to table
rinse and repeat
Based on what you have, here is a rough untested representation of what I am suggesting, I built it out of your own code, but it could be done in several ways really...
function generate_table() {
// Create our table
var table = document.createElement("TABLE");
document.body.appendChild(table);
for(var i = 0; i < query4.length; i++) {
// Set up an awesome new row.
var row = document.createElement("TR");
// Set up awesome new cells.
var nameCell = document.createElement("TD");
var numberCell = document.createElement("TD");
// Instantiate variables to hold our data.
var name = document.createTextNode(contactNameArray[i]);
var number = document.createTextNode(contactNumberArray[i]);
// Add values to cells
nameCell.appendChild(name);
numberCell.appendChild(number);
// Add cells to row.
row.appendChild(name);
row.appendChild(number);
// Build out awesome row.
table.appendChild(row);
}
}
I did a couple things here, first off some variable renaming, descriptive variable names do wonders for code readability and maintenance later on. (Check out the book "Clean Code", it talks on this at length, it changed the way I look at code virtually overnight.)
One other thing, I assume the query4 variable is being set up in the global scope, that will work, but it's typically good to try an keep the global space clear if and when you can. (See Douglas Crockfords "Javascript: The Good Parts", another great book on Javascript that really helped me learn the language.) Maybe consider passing the data to the generate table function, and calling the function in the callback of the parse data return?
Anyway, that is my "brief" two cents, hope it helps!
Good luck.

SYNTAX HELP: How to Find control in javascript ?

I am trying to implement server side code on client side. "trvddl1" is a ascx control which contains a dropdownlist "ddltree". It was easy on server side but I am facing difficulty using the same in javascript.
How do I write the following code in javascript?
((DropDownList)trvddl1.FindControl("ddltree")).SelectedValue;
I tried
var abc = document.getElementById('<%=trvddl1.ClientID%>').value;
and
var Region = document.getElementById('<%=trvddl1.FindControl("ddltree")%>').value;
but javascript returned error. Is there some other keyword I am missing ?
Check the HTML output (Browser-->View Source) and locate the control there, see what the ID of that control has, and put that one into the getElementById() function.
Example:
<input id='ddltree' .... />
Then use:
var abc = document.getElementById('ddltree').value;
Perhaps you can try something like that:
// find all controls that have an id that ends with ddltree
// starts with would be [id*=ddltree]
var abc = document.querySelectorAll("[id$=ddltree]");
if(abc.length > 0) {
// got it !
console.log(abc[0].value);
}
Please note that querySelectorAll is not supported in all browsers (even though - most). Here is a reference.

Replace all strings "<" and ">" in a variable with "<" and ">"

I am currently trying to code an input form where you can type and format a text for later use as XML entries. In order to make the HTML code XML-readable, I have to replace the code brackets with the corresponding symbol codes, i.e. < with < and > with >.
The formatted text gets transferred as HTML code with the variable inputtext, so we have for example the text
The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.
which needs to get converted into
The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.
I tried it with the .replace() function:
inputxml = inputxml.replace("<", "<");
inputxml = inputxml.replace(">", ">");
But this would just replace the first occurrence of the brackets. I'm pretty sure I need some sort of loop for this; I also tried using the each() function from jQuery (a friend recommended I looked at the jQuery package), but I'm still new to coding in general and I have troubles getting this to work.
How would you code a loop which would replace the code brackets within a variable as described above?
Additional information
You are, of course, right in the assumption that this is part of something larger. I am a graduate student in Japanese studies and currently, I am trying to visualize information about Japenese history in a more accessible way. For this, I am using the Simile Timeline API developed by MIT grad students. You can see a working test of a timeline on my homepage.
The Simile Timeline uses an API based on AJAX and Javascript. If you don't want to install the AJAX engine on your own server, you can implement the timeline API from the MIT. The data for the timeline is usually provided either by one or several XML files or JSON files. In my case, I use XML files; you can have a look at the XML structure in this example.
Within the timeline, there are so-called "events" on which you can click in order to reveal additional information within an info bubble popup. The text within those info bubbles originates from the XML source file. Now, if you want to do some HTML formatting within the info bubbles, you cannot use code bracket because those will just be displayed as plain text. It works if you use the symbol codes instead of the plain brackets, however.
The content for the timeline will be written by people absolutely and totally not accustomed to codified markup, i.e. historians, art historians, sociologists, among them several persons of age 50 and older. I have tried to explain to them how they have to format the XML file if they want to create a timeline, but they occasionally slip up and get frustrated when the timeline doesn't load because they forgot to close a bracket or to include an apostrophe.
In order to make it easier, I have tried making an easy-to-use input form where you can enter all the information and format the text WYSIWYG style and then have it converted into XML code which you just have to copy and paste into the XML source file. Most of it works, though I am still struggling with the conversion of the text markup in the main text field.
The conversion of the code brackets into symbol code is the last thing I needed to get working in order to have a working input form.
look here:
http://www.bradino.com/javascript/string-replace/
just use this regex to replace all:
str = str.replace(/\</g,"<") //for <
str = str.replace(/\>/g,">") //for >
To store an arbitrary string in XML, use the native XML capabilities of the browser. It will be a hell of a lot simpler that way, plus you will never have to think about the edge cases again (for example attribute values that contain quotes or pointy brackets).
A tip to think of when working with XML: Do never ever ever build XML from strings by concatenation if there is any way to avoid it. You will get yourself into trouble that way. There are APIs to handle XML, use them.
Going from your code, I would suggest the following:
$(function() {
$("#addbutton").click(function() {
var eventXml = XmlCreate("<event/>");
var $event = $(eventXml);
$event.attr("title", $("#titlefield").val());
$event.attr("start", [$("#bmonth").val(), $("#bday").val(), $("#byear").val()].join(" "));
if (parseInt($("#eyear").val()) > 0) {
$event.attr("end", [$("#emonth").val(), $("#eday").val(), $("#eyear").val()].join(" "));
$event.attr("isDuration", "true");
} else {
$event.attr("isDuration", "false");
}
$event.text( tinyMCE.activeEditor.getContent() );
$("#outputtext").val( XmlSerialize(eventXml) );
});
});
// helper function to create an XML DOM Document
function XmlCreate(xmlString) {
var x;
if (typeof DOMParser === "function") {
var p = new DOMParser();
x = p.parseFromString(xmlString,"text/xml");
} else {
x = new ActiveXObject("Microsoft.XMLDOM");
x.async = false;
x.loadXML(xmlString);
}
return x.documentElement;
}
// helper function to turn an XML DOM Document into a string
function XmlSerialize(xml) {
var s;
if (typeof XMLSerializer === "function") {
var x = new XMLSerializer();
s = x.serializeToString(xml);
} else {
s = xml.xml;
}
return s
}
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
You might use a regular expression with the "g" (global match) flag.
var entities = {'<': '<', '>': '>'};
'<inputtext><anotherinputext>'.replace(
/[<>]/g, function (s) {
return entities[s];
}
);
You could also surround your XML entries with the following:
<![CDATA[...]]>
See example:
<xml>
<tag><![CDATA[The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.]]></tag>
</xml>
Wikipedia Article:
http://en.wikipedia.org/wiki/CDATA
What you really need, as mentioned in comments, is to XML-encode the string. If you absolutely want to do this is Javascript, have a look at the PHP.js function htmlentities.
I created a simple JS function to replace Greater Than and Less Than characters
Here is an example dirty string: < noreply#email.com >
Here is an example cleaned string: [ noreply#email.com ]
function RemoveGLthanChar(notes) {
var regex = /<[^>](.*?)>/g;
var strBlocks = notes.match(regex);
strBlocks.forEach(function (dirtyBlock) {
let cleanBlock = dirtyBlock.replace("<", "[").replace(">", "]");
notes = notes.replace(dirtyBlock, cleanBlock);
});
return notes;
}
Call it using
$('#form1').submit(function (e) {
e.preventDefault();
var dirtyBlock = $("#comments").val();
var cleanedBlock = RemoveGLthanChar(dirtyBlock);
$("#comments").val(cleanedBlock);
this.submit();
});

Flot: Subscript text in label

I have already asked this question in offical Flot google groups, but got no answear. Maybe because it is more javascript oriented, here is the question:
I have added the following code in my code:
var j = "d";
j = j.sub();
plot1 = $.plot($("#grafTemp"), [
{label: "Rosišče (°C): T" + j + "(t) = ---.---°C"
.... the rest does not matter.
And:
legends.eq(i).text(series.label.replace(/=.*/, "= " + y.toFixed(2) +"°C"));
I was using this example:
http://people.iola.dk/olau/flot/examples/tracking.html
Now, the subscript works ok, it displays T_d fine. But when I update
the graph (when user moves mouse over graph), then it displays
<sub>d</sub>
I know that the problem is at the legends.eq(i).text....., where
it returns pure string, with literal:
<sub>
I would like to know, how it would be possible to fix this issue. So it would use html element sub properly?
Glancing at the code, it looks like you'd replace the use of text (e.g., legends.eq(i).text(...)) with html (legends.eq(i).html(...)). But you'd need to be sure that there aren't other generated bits of it that would be a problem (for instance, if this stuff generated a string that had a < or & in it, that would need to be converted to < / & respectively before being fed into the html function).

Categories

Resources