Reputation: 85
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.
Upvotes: 4
Views: 1728
Reputation: 63
change name to:
var name="'prasad'";
I'm seeing syntax error in JS Console otherwise.
Upvotes: 0
Reputation: 368
<!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>
Upvotes: 1
Reputation: 4031
Here: var name="prasad";
you change the value of the 'name' parameter maybe this is your problem. Try deleting this line and see the output.
Upvotes: 0
Reputation: 606
Remove this line, because the variable name is same as the parameter name
var name="prasad";
Upvotes: 1