How to convert html to variable in javascript? - javascript

I have problem while convert html to javascript variable.
My HTML Code
<div onclick="openfullanswer('2','Discription part','This is the code part');">
I want to create this html code dynamically, but I have the problem in quote(" and ')
I tried like below
for(i=0;i<result.length;i++)
{
strVar +="<div onclick='openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');'>Test code</div>";
}
https://jsfiddle.net/8782n60z/1/

Way 1:
You should have to change the sequence of single and double quotes and have to escape the single quotes with '\' in on-click function arguments
Please check the below snippet for more understanding.
var result=[];
var obj=new Object();
obj.ReplyID=1;
obj.Description="This is my description";
obj.Code="This is my Code Part";
result.push(obj);
strVar="";
for(i=0;i<result.length;i++)
{
strVar +='<div onclick="openfullanswer(\''+result[i].ReplyID+'\',\''+result[i].Description+'\',\''+result[i].Code+'\');">Test code</div>';
}
document.getElementById("test").innerHTML=strVar;
function openfullanswer(replyid,desc,code)
{
alert("success");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
Way 2:
Don't change the sequence of quotes.
Only change the onclick event declaration quotes from signle to double and escape double quotes with '\' and you need not have to change anything.
Please check the below snippet for more understanding.
var result=[];
var obj=new Object();
obj.ReplyID=1;
obj.Description="This is my description";
obj.Code="This is my Code Part";
result.push(obj);
strVar="";
for(i=0;i<result.length;i++)
{
strVar +="<div onclick=\"openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');\">Test code</div>";
}
document.getElementById("test").innerHTML=strVar;
function openfullanswer(replyid,desc,code)
{
alert("success");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>

strVar +="<div onclick=\"openfullanswer('"+result[i].ReplyID+"','"+result[i].Description+"','"+result[i].Code+"');\">Test code</div>";
try this.

The code you wrote produces the following:
<div onclick='openfullanswer(1,'This is my description','This is my Code Part');'>Test code</div>
The above is not valid since there are single quotes inside the value of onclick.
You will need to escape these characters.
strVar +="<div onclick=\"window.openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');\">Test code</div>";
See here an article in SO explaining this matter in detail.
See a working demo here: https://jsfiddle.net/8782n60z/3/
P.S. I changed a bit the way to declare and call the function because it gave an error.

You can use template literal
var result = [];
var obj = new Object();
obj.ReplyID = 1;
obj.Description = "This is my description";
obj.Code = "This is my Code Part";
result.push(obj);
strVar = "";
for (i = 0; i < result.length; i++) {
strVar += `<div
onclick="openfullanswer('${result[i].ReplyID}'
, '${result[i].Description}'
, '${result[i].Code}');">
Test code
</div>`;
}
function openfullanswer(replyid, desc, code) {
alert("success");
console.log(replyid, desc, code);
}
document.getElementById("test").innerHTML = strVar;
<div id="test">
</div>
jsfiddle https://jsfiddle.net/8782n60z/5/

Instead of building the string you could also use document.createElement to generate your div. And then append it to the parent #test
var result=[];
var obj=new Object();
obj.ReplyID=1;
obj.Description="This is my description";
obj.Code="This is my Code Part";
result.push(obj);
var div;
for(i=0;i<result.length;i++)
{
div = document.createElement('div');
div.innerHTML = 'Test code'
div.onclick = openfullanswer;
}
document.getElementById("test").appendChild(div);
function openfullanswer(replyid,desc,code)
{
alert("success");
}
<div id="test">
</div>

Since what you need has already been answered above, I'll just add that the way you are trying to access and manipulate DOM element is not safe or recommended way of handling dom elements. Instead of directly writing to DOM, its better to make use of addEventListner() function and bind your element to it.
For instance, instead of writing ,
strVar +="<div onclick='openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');'>Test code</div>";
you should be instead doing
strVar.outerHTML += '<input id="btncall" ...>'
document.getElementById ("btncall").addEventListener ("click", openfullanswer(parameters), false);

Related

Add a space between each character, but in a method

Hey :) I know a similiar question was asked before, but i just cant get it through. I want to create a method called something like makeMeSpaces, so my h2 text will have a space between each character.. and i might want to use it elsewhere aswell. I have this until now, from the logic point of view:
var text = "hello";
var betweenChars = ' '; // a space
document.querySelector("h1").innerHTML = (text.split('').join(betweenChars));
it also works pretty fine, but i think i want to do
<h2>Hello.makeMeSpaces()</h2>
or something like this
Thank you guys!
If you really want this in a 'reusable function,' you'd have to write your own:
function addSpaces(text) {
return text.split('').join(' ');
}
Then, elsewhere in code, you could call it like so:
var elem = document.querySelector('h2');
elem.innerHTML = addSpaces(elem.innerHTML);
Maybe this is what you want , not exactly what you showed but some what similar
Element.prototype.Spacefy = function() {
// innerText for IE < 9
// for others it's just textContent
var elem = (this.innerText) ? this.innerText : this.textContent,
// replacing HTML spaces (' ') with simple spaces (' ')
text = elem.replace(/ /g, " ");
// here , space = " " because HTML ASCII spaces are " "
space = " ",
// The output variable
output = "";
for (var i = 0; i < text.length; i++) {
// first take a character form element text
output += text[i];
// then add a space
output += space;
};
// return output
this.innerHTML = output;
};
function myFunction() {
var H1 = document.getElementById("H1");
// calling function
H1.Spacefy();
};
<h1 id="H1">
<!-- The tags inside the h1 will not be taken as text -->
<div>
Hello
</div>
</h1>
<br />
<button onclick="myFunction ()">Space-fy</button>
You can also click the button more than once :)
Note :- this script has a flow, it will not work for a nested DOM structure refer to chat to know more
Here is a link to chat if you need to discuss anything
Here is a good codepen provided by bgran which works better

Output html tag as text into a div, each array element on separate line

I have an array in javascript file called newElements.
The format likes this:
newElements: Array[3]
0: "<p class='Day'>asdasd</p>"
1: "<p class='Day'>123123</p>"
2: "<p class='Day'>Test</p>"
length: 3
And I have a div.panel-body.
What I did is
for( var i = 0; i < newElements.length; i++) {
new_content += newElements[i];
}
$(".panel-body").text(new_content);
It gives me output looks like this:
However, I want the div format like this:
<p class="Day">Some Text</p>
<p class="Day">Another Text</p>
<p class="Session">TEXT</p>
Each html tag on a separate line.
Yes, I know the <br> tag, but the question is, if I add <br> , the <br> tag will be treated as plain text, the output will become like this: <p class="Day">asdasd</p><br><p class="Day">asds</p>
So, could someone give me a nice way to show the output to screen the way I want it. You already have the array I give you.
And if I use html() function, the <p> will be treated as real html tag, that's not what I want, I want they be shown.
If you don't want to display the code, instead of .text(), use .html().
Fiddle: http://jsfiddle.net/q4AeR/
My mistake. Since you DO want to show the actual code, add each to its own new element, within the loop. This is the best I can think of:
Fiddle: http://jsfiddle.net/Hb9mC/
Try
for( var i = 0; i < newElements.length; i++) {
$(".panel-body").append(document.createTextNode(newElements[i])).append('<br/>');
}
http://jsfiddle.net/9z3zE/1/
I assume you want to display your code including line breaks. Convert your HTML to entities and add line breaks:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
var newElements = ['<p class="Day">asdasd</p>,<p class="Day">123123</p>,<p class="Day">Test</p>'],
output = '';
for(var i = 0; i < newElements.length; i++) {
output += htmlEntities(newElements[i]) + '<br />';
}
$('.panel-body').html(output);
http://jsbin.com/mefuhufo/1/edit
<div class="hello">
</div>
<script>
var mycars = new Array();
mycars[0] = "<p class='Day'>Hello Xinrui Ma</p>";
mycars[1] = "<p class='Day'>this is the array</p>";
mycars[2] = "<p class='Day'>hopes it fits your need</p>";
var divHello = $('div.hello')
$.each(mycars, function( index, value ) {
divHello.append(value);
});
</script>

return the text value of tags and append a line break to each tag

So if I call this function:
$("#item").text()
on this HTML code:
<div id="item">
<pre><span class="cm-tag"><html></span></pre><pre><span class="cm-tab"> </span>asdf</pre><pre><span class="cm-tag"></html></span></pre>
</div>
it returns:
'<html> asdf</html>'
and i want it to return:
'<html>
asdf
</html>'
basically i need a new line after each <pre> tag... how would i do this?
A possible solution, get the text of each pre and join them with new lines:
var text = $("#item pre").map(function(){
return $(this).text();
}).get().join('\n');
Here is the jsfiddle: http://jsfiddle.net/uGGFe/
Another option for you:
var clone = $("#item").clone(); //create a clone we can manipulate
clone.find('pre').after('\n'); //stick new lines in after <pre> tags
alert(clone.text()); //behold the alert glory
http://jsfiddle.net/SrV9c/1/
var text = '';
$("#item pre").map(function(i, el) {
return $(el).text().replace(/\s/g, '')
}).each(function(i, val) {
if (i == 0)
text += val.concat('\n\t');
else
text += val.concat('\n');
});
​
Working sample
because jQuery search match htmlElement use regular expression, when regular expression match content first delete "\r\n", so you see the content not have "\r\n"

Passing parameter to the javascript function fails

function test() {
var id = 123;
var id12 = 'abcd';
var childDiv = "";
childDiv += '<div style="width:20px;height:20px" onclick="newsClicked('+id12+')">Click</div>';
$("#mydiv").append(childDiv);
}
function newsClicked(param) {
alert(param);
}
Above is the test function, test() is the function which I call inside onClick event of a test div. If I pass id which is a number(integer) it works, If I pass
string it says reference error. Its related to closure I guess. How to solve it.
Whats happening actually here ?
Change:
childDiv += '<div style="width:20px;height:20px" onclick="newsClicked('+id12+')">Click</div>';
to
childDiv += '<div style="width:20px;height:20px" onclick="newsClicked(\''+id12+'\')">Click</div>';
When you append childDiv 1st one to div with integer as parameter the result will be:
<div style="width:20px;height:20px" onclick="newsClicked(3)">Click</div>
which is correct, in case of string the result will be:
<div style="width:20px;height:20px" onclick="newsClicked(string_as_arg)">Click</div>
this is not ok, because string_as_arg is not a variable at last not in the scope. That's why you should enclose it in apostrophes. Then the proper results will be:
<div style="width:20px;height:20px" onclick="newsClicked('3')">Click</div>
<div style="width:20px;height:20px" onclick="newsClicked('string_as_arg')">Click</div>
so there is no really big difference in case of integer constant but string now is properly recognised as string not as variable.
Its working when you are passing a number because the number need not be in quotes but the string has to be in quotes. so to pass string you should use escape char "\"
something like :
newsClicked(\''+id12+'\')
on you issues,
How to solve it.
*note: you can see like \''+id12+'\' on below code
function test() {
var id = 123;
var id12 = 'abcd';
var childDiv = "";
childDiv += '<div style="width:20px;height:20px" onclick="newsClicked(\''+id12+'\')">Click</div>';
$("#mydiv").append(childDiv);
}
function newsClicked(param) {
alert(param);
}
Whats happening actually here ?
newsClicked function will fired after DIV clicked which is recently added to dom,
It will added to dom like
<div onclick="newsClicked(abcd)" style="width: 20px; height: 20px;">Click</div>
here, abcd is use like variable, but does not exist on real.
And you will get error like
abcd is not defined
but if you put id variable which is integer, it will add on dom like
<div onclick="newsClicked(123)" style="width: 20px; height:20px;">Click</div>
which is totally correct on syntax wise.
I guess, you clear on this now.
Cheers,

print array with js and add html with jQuery

i want to print an array with js and just add to every element some data with html()
the code i use is :
<script type="text/javascript">
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
for(var i=0;i<testArray.length;i++){
document.write(" " +testArray[i]+"<br />").html("is the best");
}
});
</script>
but it doesnt works.
HTML:
<div id="myDIV"></div>
JS:
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
var vPool="";
jQuery.each(testArray, function(i, val) {
vPool += val + "<br /> is the best <br />";
});
//We add vPool HTML content to #myDIV
$('#myDIV').html(vPool);
});
Update:
Added demo link: http://jsfiddle.net/aGX4r/43/
Syntax problem mate!
Let me get that for you!
// first create your array
var testArray = ["test1", "test2", "test3", "test4"];
// faster ready function
$(function(){
for( var i=0; i<testArray.length; i++ ) {
current = testArray[i] + '<br />' + 'is the best'; // this is a string with html in it.
$(current).appendTo("body"); // add the html string to the body element.
}
});
First. document.write it's not a good practice.
Then, you code have a little error: Function (as in document.write) doesn't have html method. Thats a jQuery method.
So, in order to print the array in the body, you could do:
$('p').html(["test1","test2","test3","test4"].join('<br />')).appendTo(document.body);
It's a little difficult to tell what you want to do, but if you want to append to an element in your DOM, use jQuery.append();
for(var i=0;i<testArray.length;i++) {
jQuery('#mydiv').append(testArray[i]);
}

Categories