GTCrais
GTCrais

Reputation: 2087

javascript syntax - passing variable to function

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?

Upvotes: 0

Views: 260

Answers (3)

Richard
Richard

Reputation: 8280

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')
});

Upvotes: 1

user188654
user188654

Reputation:

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>';
}​

Upvotes: 0

Besnik
Besnik

Reputation: 6529

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';

Upvotes: 2

Related Questions