0

How to insert multiple parameter inside javascript function inside string.

Example:

var a = '<a onclick="my_function(parameter1, parameter2)">Click</a>';

i tried using

my_function(\''+parameter1+', '+parameter2+'\')

but not working.

Thanks all

1
  • @AnoopJoshi parameter1 is number, parameter2 is random string with -. Thanks Commented Jun 16, 2015 at 12:28

2 Answers 2

2

As you are using jQuery create elements using it and also bind event using it. Here in example I have used .data() to store arbitrary value which can be fetched in the click handler

var a = $('<a>Click</a>')
        .data('parameter1', parameter1)
        .data('parameter2', parameter2)
        .on('click', function(){
            var parameter1 = $(this).data('parameter1');
            var parameter2 = $(this).data('parameter2');
            my_function(parameter1, parameter2)
        });

For immediate problem, you need to escape quotes properly

var a = '<a onclick="my_function(\''+ parameter1 + '\',\'' parameter2 + '\')">Click</a>';

As per comment parameter1 is a number you don't need to wrap it.

var a = '<a onclick="my_function('+ parameter1 + ',\'' parameter2 + '\')">Click</a>';
Sign up to request clarification or add additional context in comments.

Comments

1

Why not:

var a = document.createElement('a');
a.innerHTML = "Click";
a.onclick = function(p1, p2) { ... your code here }

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.