4

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.

4
  • Usually when you cannot call JS from within HTML it means there is a JS error, open the JS console and look Commented Jan 14, 2014 at 6:44
  • BTW: It works on JSFiddle - jsfiddle.net/#&togetherjs=wHI6Ep7zgl Commented Jan 14, 2014 at 6:45
  • I tried your code and it's working... (Good practice : do not declare the same variable twice : name. It was already declared as a param. So, just affect the new value without the "var" tag.) Commented Jan 14, 2014 at 6:47
  • You should use innerHTML property instead document.write(). Check this fiddle: jsfiddle.net/NU2yF Commented Jan 14, 2014 at 7:01

4 Answers 4

1
<!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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you all for you prompt response
1

Remove this line, because the variable name is same as the parameter name

var name="prasad";

Comments

0

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.

Comments

0

change name to:

var name="'prasad'";

I'm seeing syntax error in JS Console otherwise.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.