Creating Anonymous Function With Variable?
Mar 20, 2010
I'm having trouble with something that I can't explain outside of an example. Code:
Code:
$js_info_tabs = json_encode($valid_array);
$script = <<<JAVASCRIPT
<script type="text/javascript">//<![CDATA[
function changeTo(id) {
[Code]....
I have the code this way in order to consolidate it since I would prefer to do that instead of checking the selected ID and manually checking against all possible IDs (which works flawlessly, it just takes up about 5x the lines and is not modular). What I have above also works, but there is one fatal flaw:
It seems like the anonymous function that is the onclick for each unselected element becomes "return changeTo(tab + '_id')", but I don't want it to be that. I want the argument to actually be what tab is instead of the variable.
What ends up happening is that after changeTo() is called for the first time, any element you click will result in the last element being the selected one, as if it's using the final value of tab as its return value.
This doesn't make any sense, though, since tab is local, and deleting it before the function exists doesn't work. Deleting elem at the end of the for loop doesn't work. I honestly don't understand what's going on or why it doesn't set the new onclick value correctly.
Basically I just want changeTo(tab + '_id'); to turn into changeTo('MYID_id'); instead, but it simply doesn't do that and I can't figure out a way how.
View 1 Replies
ADVERTISEMENT
Oct 29, 2009
I would like to store a variable then call it back later. I have a variable on line 198
www = ''+this._ad.clickUrl+'';
And on line 321 I try
document.write(www);
I've tried so many different options, just won't work. I have even tried to call document.write(window.www);
The code is below.. might be easier to read on [URL]
Code:
<html><head>
<title>Integrated Ad Sample</title>
<!-- NOTE MANDATORY jQuery Include -->
<script type="text/javascript" src="[URL]">
</script><!-- Integrated Ad Include-->
<script type="text/javascript"> .....
View 2 Replies
View Related
Jul 25, 2011
I think the last thing people seem to learn about in JavaScript when they're not coming from other programming languages is variable scope. Some even get all the way into AJAX without having learned about scope, and this is a time when it's really needed. Although the scope of JavaScript variables is non-complex by nature, it's something we should all get a full understanding for before we move too far.
Section 1: What is "scope"?
Section 2: The "var" keyword
Section 3: The "this" keyword
Section 4: Closures or "Anonymous functions and self-invoking closures
View 5 Replies
View Related
Feb 3, 2011
I have a problem with understanding jQuery. In my case I have this JS file with following content (see below). This is an anonymous function, isn't it? The problem is this line:
[Code]...
View 1 Replies
View Related
Jan 8, 2011
I have been struggling with a form wizard all day. I'm using jquery stepy (form wizard) along with validation plugin. To cut a long story short, my first step is to get MySQL connection from form controls details. On submit ('next' button) a check is made on an empty hidden control ('hid').
rules: {
hid: {
required: function(){
return checkDBData();
},
messages: {
hid:
{required: 'SQL not available'},
...(etc)...
So, if the function checkDBData passes, false should be returned, so that the form can progress to the next step. If the connection details fail, true is returned so that an error msg is posted.
Here's the checkDBData function:
function checkDBData(){
var host = $('#mysql_host').val();
var username = $('#username').val();
var password = $('#password').val();
var dbname = $('#dbname').val();
$.post("install/sqlcheck.php",
{"host": host,"username": username, "password": password, "dbname": dbname},
function(msg){
if(msg.required == false){
return false;
}else{
return true;
}},
"json"
);
}
The return values don't find their way back to the rules. However, if I hard code false and true to the function...
function checkDBData(){
var host = $('#mysql_host').val();
var username = $('#username').val();
var password = $('#password').val();
var dbname = $('#dbname').val();
$.post("install/sqlcheck.php",
{"host": host,"username": username, "password": password, "dbname": dbname},
function(msg){
if(msg.required == false){
return false;
}else{
return true;
}},
"json"
);
return false; //or return true for testing purposes
}
This works. I assume it's due to the asynchronous nature of the ajax call.
View 2 Replies
View Related
Nov 3, 2011
var name = "good";
load_image( name );
function load_image( name )
[code]....
I've tried giving addEventListerner an anonymous function
View 3 Replies
View Related
Dec 4, 2006
I have several functions with code along the lines of:
var xmlDoc = requestXML("ajax.asp?SP=SelectRelatedTags&tag=" +
array[i]);
The requestXML() function includes the code:
var xmlDoc = null;
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xmlDoc = http_request.responseXML;
} else {
alert('There was a problem with the request.' +
http_request.status);
}}};
http_request.open('GET', url, true);
http_request.send(null);
return xmlDoc;
However, the last line (the return) executes before the readyState
reaches 4. How do I return the xmlDoc to the functions only once the
xmlDoc has been assigned? I tried putting the return statement in a
while loop with the condition that the readyState must = 4 - this
worked, but makes the browser popup a message saying the script is
slowing down the system.
View 1 Replies
View Related
Jun 6, 2009
I did search the forums but couldn't seem to find anything on this specifically. I basically need to pass a key event and a 'name' to nameCheck() after 3 seconds. This works fine in Firefox but Internet Explorer gives the error: Member not found. I'm more of a PHP guy than a JS one
<input type="text" onkeyup="nameCheckTimer(this.value, event)" value="" />
function nameCheckTimer(name, evt) {
setTimeout(function(){return nameCheck(name,evt)}, 3000);
}
function nameCheck(name, evt) {
//need name and the key event to be available here. I have code to handle the key codes which works fine
}
View 6 Replies
View Related
Jun 10, 2010
I'm working with nested functions and trying to pass a 'this' value to an anonymous being used in an assignment for an event listener.So, this should plop a button inside our DIV and when clicked I'd like it to run the alert-ding; unfortunately it seems to want to run the function as defined under the buttons object which doesn't work out too well.
View 3 Replies
View Related
Aug 2, 2010
I would like to know how to pass in a reference of this to anonymous function so I can access parameters from anonymous. Here is my code:
[Code]...
View 2 Replies
View Related
Oct 16, 2010
I am confused about the true difference between the two below examples.
first example:
// Demonstrating a problem with closures and loops
var myArray = [“Apple”, “Car”, “Tree”, “Castle”];
var closureArray = new Array();
[code]....
Here we iterate through the length of myArray, assigning the current index of myArray to theItem variable. We declare closureArray 4 times as an anonymous function. The anonymous function in turn declares the predefined write() function, which is passed parameters. Since write() is in closureArray() a closure is created??? During each iteration, theItem is reassigned its value. The four closures reference this value. Since they reference this same value and since this value is reassigned ultimately to the value of the fourth index position, tHe time we execute closureArray later on, all four closures output the same string. This is because all four closures are within the same scope "the same environment" and therefore are referencing the same local variable, which has changed.
I have a couple of problems with this example:
1) I thought a closure is a function that is returned - the inner function is not returned above.
2) theItem is not even a local variable of the parent function (closureArray) - I thought in order for a closure to work, the inner function only accesses the local variables of the outer function, but in this case the local variable is defined OUTSIDE of the parent function.
3) the "the four closures are sharing the same environment." The thing is even in the second example, they are sharing the same environment.
Second example:
// A correct use of closures within loops
var myArray = [“Apple”, “Car”, “Tree”, “Castle”];
var closureArray = new Array();
[code]....
Here we iterate over the length of myArray (4 times), assigning the index of myArray to theItem variable. We also return a function reference to the closureArray during each iteration (closureArray[i]), where i is index number so we assign 4 functon references. So when we iterate through myArray, we immediatelly call the writeItem() fucntion passing an argument of theItem at its current value. This returns a child anonymous function and when that child function is called, it will execute a block that calls the predefined write() method. We assign that returned anonymous function to the variable closureArray. Hence, closureArray holds a reference to that anonymous function. So closureArray during each iteration holds a reference to the anonymous function and we later call closureArray, which in turn calls the anonymous function, therefore calling the predefined write() function to output the local variable of the parent function. This outputs each distinct index of myArray.
This is because since we created the closure, when we call writeItem, passing theItem argument, since theItem is a local variable of the parent function of the closure, it is never destroyed when we later call closureArray (the reference to the child anonymous function)? Yet weren't we using a closure in the first example as well? So whey wasn't those variables preserved?
I don't think it has anything to do with assigning a returned anonymous function to closureArray. Even though an anonymous function creates a new memory position in the javascript engine, therefore not overwriting the other function references we create during the iteration, it's still referring to a local variable declared outside the reference. So if it's about the closure retaining value of parent's local variable even after exiting the parent function allowing for the current indexes to be preserved, then why did the closure in the first example fail to retain each index?
View 7 Replies
View Related
Feb 28, 2010
I am trying to create an anonymous function for onchange event of file field, so that when a file is selected, the covering text field gets that value. I know how to accomplish this by adding onchange="", but I'd prefer not do that. The code that I have almost works, except that the function in the for loop can't call on the "i" variable that the loop uses.
for( i = 0; i < source.length; i++) {
source[i].onchange = function() {
name[i].value = this.value;
}
}
View 3 Replies
View Related
Oct 22, 2010
//<input type="text" id="s_field" value=""/>
var valid = true;
var div = $("#s_field");
$.post("index.php",{id: 6}, function (data){
[Code]..
When posting data, and getting response need to set valid to false - email is not valid.
1. in function it alerts valid is false
2. outside function it says valid is still true!
even i didn't wrote var valid = false;, but valid = false;I need to set Global "valid" variable to false.
View 1 Replies
View Related
Mar 28, 2010
I'm using jquery to make it easy for AJAX calls.
So I create a class: function cMap(mapID){//vars and stuff}
I go and prototype a function: cMap.prototype.loadMap = function(){ //jquery AJAX call }
Now in the jquery $.ajax({...}); call, I use an anonymous function on the "success:" call: success: function(data){ this.member = data; }
My problem is that inside this anonymous function call I'm trying to call a class member of my cMap class to store the data in from the AJAX call, but it's out of scope. So the JS console in FF/Chrome throws errors about bad value/doesn't exist.
How can I access this class member from inside an anonymous function? Or at least what's a good way to go about doing all this?
View 2 Replies
View Related
Jan 7, 2010
I'm trying to create a family tree online that has several other related family charts. I want each person's name and birth year to be stored in javascript variables, then I want to be able to just go through the tree, and put the persons name once, and have it put the appropriate name and birthyear in the little boxes that the css is creating.
var johnname = "John Smith";
var johnbirthyear = "Jan 1 1930";
var janename = "Jane Doe";
[code]....
So I thought I had it all figured out. I thought that the above would take the id of John that I added, go to the line that sets the name, add john to the word name, and then document write the variable of johnname from the js file. I know you're laughing at me because of course it instead made the value of name to johnname, then wrote the word johnname in the box. I want to go through and be able to just type the persons name in the html for that box once, and have it update with their appropriate info.
View 8 Replies
View Related
Jul 30, 2010
String.prototype.trim = function(){
return this.replace(/^s+|s+$/g, "");
}
[code]....
It's possible with numbers:
var myNum = 10;
myNum++;
alert(myNum); //11
View 4 Replies
View Related
Apr 12, 2011
I'm using a form data reference, something like P-1234 for example to create a text file and a link to the file. This is during the construction of a new table or table row with javascript. I have an array of one or more references submitted via form using $_POST. On my action page I am creating a txt file P-1234. If I am creating a table ot table row using createElement(), one of the cells will have a link to the file. If the file is created as follows:
$File = $_POST['ref'][$i] . "txt";
After creating the cell
var Cell = document.createElement('td');
[code]....
I assume the link is inserted using innerHTML? If so, do I just append the filename to the end of the file path like this?
Cell.innerHTML = "http://localhost/Project/+File";
View 1 Replies
View Related
Nov 6, 2009
I'm trying to build a page that shows random, alternating divs, and have looked at this page as an example. However, the issue at the moment is that although the divs display randomly, they do not disappear in order.The finished "page" is to be referenced by another page that I do not have control over. Here is the section of the file containing JavaScript:
<script type="text/javascript">
var curcontentindex=0
var messages=new Array()
[code]....
I've found very little info on how to reference a previous variable...maybe create an array to store them in, but wasn't sure how to go to the previous value in the array.
View 3 Replies
View Related
Aug 9, 2003
Here's my problem: I need to create a variable name dynamically, made up of a string (say "var_name_") and an integer. Ultimately I want something like this:
var_name_1 = 'whatever value I want'
var_name_2 = 'whatever value I want'
var_name_3 = 'whatever value I want'
...
var_name_N = 'whatever value I want'
But the actual variable names are determined at run-time, so I can't just hardcode them.
Any suggestions? JavaScript doesn't seem to have a Variable type, so I can't just cast a string into a var...
View 4 Replies
View Related
Aug 10, 2010
var x = "blahblah".indexOf("blahblah");
if (x !== -1){
// do something with x
[Code].....
Is there some syntax/code structure that allows something like this:
if ( (var x = "blahblah".indexOf("blahblah")) !== -1){
// do something with x
alert("Present");
[Code]....
View 3 Replies
View Related
Aug 16, 2011
I'd like to use $.post to create php session variables on the fly when a link is clicked, and then let the browser follow the href content.
[Code]...
View 4 Replies
View Related
Aug 31, 2010
I am probably going about this all wrong, but I'm not sure how to do this.Basically I need to create a unique variable name for each element that has the same class name and set each one to zero.I thought I could just concatenate the index value to a variable name to create unique names. Something like:
$('.toggle-trigger').each(function(){
var toggleTriggerIndex = $('.toggle-trigger').index(this);
var t + toggleTriggerIndex = 0;
[code]....
View 1 Replies
View Related
Apr 10, 2011
I am working on a javascript for my blackberry. I am trying to capture the latitude and longitude of that phone. I am able to get the coordinates in an alert box but am having a little trouble writing it to a form input field.
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN" "[URL]">
<html xmlns="[URL]" xml:lang="en" lang="en">
<head><title>GPS Testing</title>
</head><body>
<script type="text/javascript">
if(blackberry.location.GPSSupported){
document.write("Your device supports GPS locating");
blackberry.location.onLocationUpdate(window.alert("Latitude: " + blackberry.location.latitude + " Longitude: " + blackberry.location.longitude));
var lat = blackberry.location.latitude();
var lng = blackberry.location.longitude();
blackberry.location.refreshLocation();
document.write(lat);
}
</script></body></html>
I am only able to test with Blackberry. I was trying to create a couple of variables with the "var lat =" and var lng =".
With this script I get the alert window and when I click ok it writes "Your device supports ...".
View 5 Replies
View Related
Aug 17, 2010
I am trying to declare a variable inside a function and use it later on in my code... but it just already returns white space... i.e. not variable value. I am setting it within this function:
function show_video1(){
document.getElementById('video1').style.display="block";
var video1Name = "Education World News (Part 1)";
document.getElementById('video2').style.display="none";
document.getElementById('video3').style.display="none";
document.getElementById('video4').style.display="none";
[Code]...
and trying to call it later on with this: <script type="text/javascript">document.write(video1Name)</script> It might be worth noting that each one of my 11 videos will hace a different name.
View 13 Replies
View Related
Jul 7, 2007
There exists anonymous function, and you could also use a variable to contain such function. But why no class?
I mean, you could do:
$func = create_function('$a', 'print $a;');
$func();
or
function test($a)
{
print $a;
}
$func = 'test'
call_user_func($func, xx);
But there is no:
$class = create_class('', '');
or
$class = 'MyClass'
class $class {}
Why?
View 1 Replies
View Related
Sep 29, 2007
I'm trying to create a function in JavaScript using Dreamweaver8 such that when a user hits the ' F1' key when a text box is selected a separate "pop-up" window will open, with text of my choice.
Does anybody have any pointers or even some source code? I use ASP on my server.
View 12 Replies
View Related