Merbin Jo Merbin Jo - 2 months ago 6
HTML Question

How to convert html to variable in 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/

Answer

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>

Comments