Javascript to render kbd tagged elements - javascript

I would like to write a (Javascript?) function to be included in HTML pages that allows me to render the function arguments tagged as kbd separated by "+"s and able to take an arbitrary number of input arguments.
So, for example, fnRenderKBD(Ctrl+X, Y, Z) would render as Ctrl+X+Y+Z.
The important thing is that the function should be able to take a variable number of arguments.
Is it possible to write such a function (if so, how)? I have next to no knowledge of JS.

My answer at the bottom is not the best thing I have ever written. A better solution would look something like:
function fnRenderKBD(elem, keysToDisplay) {
var delimiter = '';
var content = null;
for(var i = 0, length = keysToDisplay.length; i < length; i++) {
var renderedKey = document.createElement('kbd');
renderedKey = setText(renderedKey, keysToDisplay[i]);
if (i > 0) {
elem.appendChild(document.createTextNode('+'));
}
elem.appendChild(renderedKey);
}
}
function setText(elem, text) {
if (elem.textContent){
elem.textContent = text;
}else{
elem.innerText = text;
}
return elem;
}
(function() {
var keys = [
'Ctrl+X',
'Y',
'Z'
];
var elem = document.getElementById('display');
fnRenderKBD(elem, keys);
}());​
Demo: http://jsfiddle.net/wPg7z/
Something like this should work:
function fnRenderKBD(elem, keysToDisplay)
{
var delimiter = '';
var content = '';
for(var i = 0, length = keysToDisplay.length; i < length; i++) {
content+= delimiter + '<kbd>' + keysToDisplay[i] + '</kbd>';
delimiter = '+';
}
elem.innerHTML = content;
}
(function() {
var keys = [
'Ctrl+X',
'Y',
'Z'
];
var elem = document.getElementById('display');
fnRenderKBD(elem, keys);
})();
​
Demo: http://jsfiddle.net/gTYxP/1/

Related

Unable to parse json using javascript

I have a json which i'm trying to parse it using javascript. Iteration count and the pages getting appended to it are going to be dynamic.
Expected Result
Just like the above image i'm able to take dynamic iteration keys from the below mentioned json.
Iteration.json
{
"count":[
{
"iteration1":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
},
{
"iteration2":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
}
]
}
When i click on iteration it has to populate the corresponding pagenames for that particular iteration as shown in expected result image. But what i get actually is (refer the image below):
Please find the code that i tried:
var pagenamearray = [];
$.getJSON("iteration.json", function(json) {
var hits = json.count;
var iterations, tnname, iteration;
for (var k in hits) {
var value;
if (hits.hasOwnProperty(k)) {
value = hits[k];
var iteratearray = [];
for (var j in value) {
if (value.hasOwnProperty(j)) {
j;
var check = value[j];
for (var i in check) {
if (check.hasOwnProperty(i)) {
var test = check[i];
for (var t in test) {
if (test.hasOwnProperty(t)) {
var pagename = JSON.stringify(t)
var arr = []
if (pagename.includes("PageName")) {
//alert("Key is " +pagename + ", value is" + JSON.stringify(test[t]));
for (var it = 0; it < hits.length; it++) {
if ((Object.keys(hits[it])).includes(j)) {
var pagenamevalue = test[t];
arr[it] = [];
arr.push(pagenamevalue);
}
}
}
//alert(arr)
}
pagenamearray.push(arr);
}
}
}
}
var row = document.createElement('div');
row.setAttribute("class", "row");
row.setAttribute("id", j)
var gridWidth = document.createElement('div');
gridWidth.setAttribute("class", "col-lg-12");
var panelRoot = document.createElement('div');
panelRoot.setAttribute("class", "panel panel-default");
var panelHeading = document.createElement('div');
panelHeading.setAttribute("class", "panel-heading");
var heading3 = document.createElement('a');
heading3.setAttribute("class", "panel-title");
var icon = document.createElement('i');
icon.setAttribute("class", "fa fa-long-arrow-right fa-fw");
heading3.appendChild(icon);
heading3.innerHTML = j;
heading3.setAttribute("onclick", "doit('" + j + "');");
panelHeading.appendChild(heading3);
/* var panelBody=document.createElement('div');
panelBody.setAttribute("class","panel-body");
panelBody.setAttribute("id","panellinks");*/
panelRoot.appendChild(panelHeading);
// panelRoot.appendChild(panelBody)
gridWidth.appendChild(panelRoot);
row.appendChild(gridWidth);
document.getElementById("analysis").appendChild(row);
}
}
}
});
function doit(value) {
var ul = document.getElementById(value);
if (ul != undefined) {
$("#" + "expandlinks").remove();
$("#" + value + value).remove();
}
var accordion = document.getElementById(value);
var panelBody = document.createElement('div');
panelBody.setAttribute("class", "panel-body");
panelBody.setAttribute("id", "expandlinks")
var tablediv = document.createElement('div')
var tablelink = document.createElement('a');
tablediv.appendChild(tablelink);
var graphdiv = document.createElement('div')
var graphlink = document.createElement('a');
graphdiv.appendChild(graphlink);
var recommndiv = document.createElement('div');
var recommendlink = document.createElement('a');
recommndiv.appendChild(recommendlink)
//alert(pagenamearray.length)
tablelink.innerHTML = pagenamearray;
/*graphlink.innerHTML="Timeline View";
recommendlink.innerHTML="Recommendations";*/
panelBody.appendChild(tablediv);
panelBody.appendChild(recommndiv);
panelBody.appendChild(graphdiv);
accordion.appendChild(panelBody);
}
Any advise on how to achieve this would be of great help. Thanks in advance.
I think the problem is how you assign the pagenamearray to tablelink.innerHTML. This converts the array to a string, converting all elements in the array to a string too and separating them by a comma each. However, your pagenamearray contains some empty arrays too; these will convert to an empty string in the process, but will still have a comma before and after them.
In your example code above, the pagenamearray will end up with a value of [[[],"T01_Launch"],[[],"T02_Login"],[null,[],"T01_Launch"],[null,[],"T02_Login"]] - when converted to a String, this will result in ",T01_Launch,,T02_Login,,,T01_Launch,,,T02_Login". So instead of assigning it to the innerHTML value directly, you'll first have to filter out the empty arrays and null values.

Add and remove separators to urls by javascript

I have links on page and want mask them. I want,
that at onLoad all points in urls (which are in href) will be replaced with something like "|",
so instead of
link
there is somehting like
link.
Then, at onClick replacements should be reversed to make links working again.
Need help to get this code to work:
function mask() {
var str = document.getElementByName("a");
var x = str.attributes.href.value.replace('.', '"|"');
document.getElementsByTagName("a").attributes.href.value = x;
}
function unmask(){
var str = document.getElementByName("a");
var x = str.attributes.href.value.replace('"|"', '.');
document.getElementsByTagName("a").attributes.href.value = x;
}
<body onLoad="mask()">
link
</body>
You have to use the getElementsByTagName method:
function mask() {
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
a[i].attributes.href.value = a[i].attributes.href.value.replace(/\./g, '"|"');
}
}
function unmask() {
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
a[i].attributes.href.value = a[i].attributes.href.value.replace(/"\|"/g, '.');
}
}
<body onLoad="mask()">
link
</body>
There are several issues in your code:
document.getElementByName("a") is not valid
str.attributes.href.value is not valid
You need to go global replace to replace all the . with | and vice-versa.
function mask() {
var str = document.getElementsByTagName("a")[0];
var x = str.href.replace(/\./g, '"|"');
str.href = x;
}
function unmask(){
var str = document.getElementsByTagName("a")[0];
var x = str.href.value.replace(/"|"/g, '.');
str.href = x;
}
<body onLoad="mask()">
link
</body>

How to output Javascript string with character encoding

So - I have a string in javascript liks so:
var foo = "Hello™";
I need to print this out in HTML (via JS) so it looks like this:
Hello™
Sounds easy, but I obviously am missing something cause I can't figure out a simple solution for it yet.
EDIT - here is more code:
var label = document.createElement('label');
var foo = selectData.options[i][1]; // this is "Hello&trade";
label.innerHTML = foo;
container.appendChild( label );
Just append it into the innerHTML property.
innerHTML will html encode the given input and that append it to the node.
var foo = "Hello™";
document.getElementById('label').innerHTML = foo;
<label id="label"></label>
First separate the '&trade' and check for it in an if-statement and then give var the value of the hexcode equivalent which is 'u2122' then the rest of the code should do the work.
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
String.prototype.hexDecode = function(){
var j;
var hexes = this.match(/.{1,4}/g) || [];
var back = "";
for(j = 0; j<hexes.length; j++) {
back += String.fromCharCode(parseInt(hexes[j], 16));
}
return back;
}
var str = "\u2122";
var newStr = (str.hexEncode().hexDecode());
var foo = "Hello" + newStr;
console.log(foo);

pushing into arrays in javascript

My script (is meant to) grab text from the a page (which works fine) and then splits it by by newline (\n) and puts each splitted string into an array called "dnaSequence"; from there it loops through each element in the array and if the string contains the character ">" it assigns that string to the "var header_name", else it pushes all other lines into a new array called "dnaSubseq". The original text looks something like this:
>header_1
gctagctagc
cgcgagcgagc
>header_2
gcgcatgcgac
When I execute the code it fails to alert on anything. Here is the code:
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.pushValues(dnaSequence[i]);
}
alert(dnaSubseq);
}
}
Change
dnaSubseq.pushValues(dnaSequence[i]);
To
dnaSubseq.push(dnaSequence[i]);
If it doesn't alert anything, that means you forgot to invoke the function :)
loaderMy();
http://jsfiddle.net/zszyg5qx/
Try this function
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.push(dnaSequence[i]);
}
alert(dnaSubseq);
}
}

getElementByName & Regex

How do I loop through all elements using regular expression in getElementByName?
If you mean like:
var elementArray = document.getElementsByName("/regexhere/");
then no that would not be possible.
To do what you want to do you would have to get all the elements, then go through each one and check the name of it.
Heres a function that will go through all the elements and add all the elements with a certain name to an array:
function findElements(name)
{
var elArray = [];
var tmp = document.getElementsByTagName("*");
var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].name) ) {
elArray.push(tmp[i]);
}
}
return elArray;
}
And use as:
var elName = "customcontrol";
var elArray = customcontrol(elName);
Or it might be easier by className
function findElements(className)
{
var elArray = [];
var tmp = document.getElementsByTagName("*");
var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].className) ) {
elArray.push(tmp[i]);
}
}
return elArray;
}
And use as:
var elClassName = "classname";
var elArray;
if (!document.getElementsByClassName)
{
elArray= findElements(elClassName );
}
else
{
elArray = document.getElementsByClassName(elClassName);
}
This would do what you want, without the need for getElementByName.
Although I think you meant getElementsByName
If you wanted to look for an element with only the name "customcontrol" you would use:
var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
If you wanted to look for an element with that STARTED with the name "customcontrol" you would use:
var regex = new RegExp("(^|\\s)" + name);
EDIT:
If your using jQuery, which would be easier, then this would do:
var elArray = $("*[name^='customcontrol']");
//Use JavaScript to loop through
for (var a = 0; a< elArray.length;a++)
{
//Loop through each element
alert(elArray[a]);
}
//Or
$("*[name^='customcontrol']").css("color","red"); //Or whatever you want to do to the elements
Use a custom selector in jQuery. You probably want an example with parameters.

Categories

Resources