Aaliya Aaliya - 15 days ago 8
HTML Question

Not able to call javascript function in dynamically generated HTML

I am not able to call the javascript function with parameter in dynamically generated HTML code.

The same function gets called successfully when I don't pass any parameter, but with parameters the function call fails. Not sure whether it is a syntax error.

below is my code:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to call a function with arguments</p>
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job) {
var name="prasad";
var str='<a href="#" onclick="javascript: fun('+name+')">link</a>';
document.write(str);
};

function fun(id1) {
alert("fun menthod "+id1);
}
</script>
</body>
</html>


If I don't pass the parameter it gets called successfully.

Shn Shn
Answer
<!DOCTYPE html>
<html>
<body>
<div id="next">
<p>Click the button to call a function with arguments</p>
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
</div>
<script>
function myFunction(name,job)
{
var a='"';
a=a+name+a;
var str="<a href='#' onclick='fun("+a+")'>link</a>";
document.getElementById('next').innerHTML=str;
}
function fun(id1)
{
alert("fun menthod "+id1);
}
</script>
</body>
</html>