Tom
Tom

Reputation: 2634

jquery function scope

I'm not understanding function scope here. I have a button when clicked shows a dialog with a textarea. Inside that textarea I populate it with a url that someone can then copy for their camera setup.

<button id="axis-details" onclick="apikey('<?php echo $result_cameras[$i]["camera_hash"]; ?>');">API Key</button>

function apikey(camerahash)
{
   var $key = "http://myhost.com/notify.php/" +camerahash;
   return $key;
}

$(document).ready(function() {
   var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ')
       .append('<p><textarea id=\"textbox\">'+apikey(camerahash)+'</textarea></p>') //ERROR here that camerahash is not defined
       .append('<p>For more information see: <a href=\"http://www.myhost.com/forum/2-quickstart-docs\">setup</a></p>');
$dialog.dialog({
    autoOpen: false,
    title: 'API Key'
});

$('#axis-details').click(function(e) {
    e.preventDefault();
    $dialog.dialog('open');
});
});

Function apikey(camerahash) does return the value I expect. I get an error indicated above that camerahash is not defined. What am I doing wrong?

Upvotes: 0

Views: 219

Answers (2)

Lazarus
Lazarus

Reputation: 43064

I think this is what you actually want:

<button id="axis-details">API Key</button>

function apikey(camerahash)
{
   var $key = "http://myhost.com/notify.php/" +camerahash;
   return $key;
}

$(document).ready(function() {
   var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ')
       .append('<p><textarea id=\"textbox\">'+apikey(<?php echo $result_cameras[$i]["camera_hash"]; ?>)+'</textarea></p>') //ERROR here that camerahash is not defined
       .append('<p>For more information see: <a href=\"http://www.myhost.com/forum/2-quickstart-docs\">setup</a></p>');
$dialog.dialog({
    autoOpen: false,
    title: 'API Key'
});

$('#axis-details').click(function(e) {
    e.preventDefault();
    $dialog.dialog('open');
});
});

Upvotes: 2

Andrew
Andrew

Reputation: 13853

It is only defined in your apikey function, you need to also pass it in from your jquery method,

 .append('<p><textarea id=\"textbox\">'+apikey('<?php echo $result_cameras[$i]["camera_hash"]; ?>')+'</textarea></p>')

Or even easier, modify your function to not need the input,

function apikey()
{
   var $key = "http://myhost.com/notify.php/" +'<?php echo $result_cameras[$i]["camera_hash"]; ?>';
   return $key;
}

Upvotes: 2

Related Questions