0
var testvar = "something";

//only one of the following 3 lines were uncommented while testing:
var myinsert = '<span class="green myCursor" 
                   onClick="getproblemsadmin(testvar)">
                   Test
                </span>'; //doesn't pass testvar to function

var myinsert = '<span class="green myCursor" 
                   onClick="getproblemsadmin(\'testvar\')">
                   Test
                </span>'; //doesn't pass testvar to function

var myinsert = "<span class='green myCursor' 
                   onClick='getproblemsadmin(\"testvar\")\'>
                   Test
                </span>"; //doesn't pass testvar to function

$('.someclass').html(myinsert); //jquery works and this works (tested)

Is there a way to pass a variable to function like this?

2
  • Do you want the value of testvar at the time of creating the string and setting the HTML, or at the time of the actual onclick event execution? Commented Jul 14, 2012 at 13:13
  • 1
    at the time of creating the string. The first answer that was posted is correct. Commented Jul 14, 2012 at 13:23

3 Answers 3

2

Do you mean the value of this variable?

var myinsert = "<span class='green myCursor' onClick='getproblemsadmin(\""+testvar+"\")\'>Test</span>";

The syntax:

var myinsert = "string" + variable + "string";
var myinsert = 'string' + variable + 'string';
Sign up to request clarification or add additional context in comments.

3 Comments

The value, yes. Thanks, I will try this out now.
This works, thanks! (I would edit my previous comment but I can't anymore)
Richard's jQuery solution is wiser, safer and faster than building a string, especially if that string includes JavaScript that will later be evaluated.
1

You could try creating the span element and then binding the click event:

$('<span class="green myCursor">Test</span>').click(function()
{
    getproblemsadmin('testvar')
});

or, if you wanted to get really jQuery'esk, you could write:

$('<span />').addClass('green myCursor').text('test').click(function()
{
    getproblemsadmin('testvar')
});

Comments

0

If I understood you correctly you are looking for a way to pass a variable to a function which will return a constructed string containing markup code? Something like this?

var testvar = "something";

var myinsert = work_horse(testvar);
$('.someclass').html(myinsert);

function work_horse(testvar){
    return '<span class="green myCursor" onClick="getproblemsadmin(' + testvar + ')">Test</span>';
}​

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.