get value from one function to another function using javascript - javascript

i want to get value from one function to the another function. and i want to pass the value to handler page. but in that i cant get the value to pass .. here i had given the code. please help me. for example assume that for radio=MR & fname=john.
function getdata()
{
alert('hi');
var radio = document.getElementsByName("radiobuttonlist1");
for (var i = 0; i < radio.length; i++)
{
if (radio[i].checked)
alert(radio[i].value);
}
var fname=document.getElementById("Firstnametxt").value;
alert(fname);
}
here i want to get all those values to another function this is my another function.
function sendinfo()
{
getdata();
$(document).ready(function(){
var url="Handler.ashx?radio="+radio+"&fname="+fname+""; "here i want the values from above function"
alert(url);
$.getJSON(url,function(json)
{
$.each(json,function(i,weed)
{
});
});
});
}
thank you . help me

You can do this two ways.
Option 1
You can define those variables outside of both functions like:
var radio;
var fname;
getdata() {
radio = document.getElementsByName("radiobuttonlist1");
fname=document.getElementById("Firstnametxt").value;
// VALUE UPDATED HERE
}
sendinfo() {
// VARIABLE ACCESSIBLE HERE
}
And then whenever the values of those variables is updated it will be updated at the scope those variables were initially defined (outside those functions).
The scope of a javascript variable is within the curly braces {} that variable is in and any curly braces within that set. Scope in javascript often refers to those curly braces {}. There are exceptions including the if statement in which you can define variables inside of and access outside (assuming the condition was true).
Option 2
Or you can pass those variables as parameters to the second function like: sendinfo(radio, fname);
Passing values by returning them
You can return the values as an object literal in your getdata() function like this:
getdata() {
return {
radio : document.getElementsByName("radiobuttonlist1"),
fname : document.getElementById("Firstnametxt").value
}
}
Then do this:
sendinfo() {
var data = getdata();
}
And then access those variables like: data.radio and data.fname.

You can declare two variables globally,set them to the values you need in the first function and access them in the second function.

var radio;
var fname;
function getdata()
{
alert('hi');
radio = document.getElementsByName("radiobuttonlist1");
for (var i = 0; i < radio.length; i++)
{
if (radio[i].checked)
alert(radio[i].value);
}
fname=document.getElementById("Firstnametxt").value;
alert(fname);
}
function sendinfo()
{
getdata();
$(document).ready(function(){
var url="Handler.ashx?radio="+radio+"&fname="+fname+""; "here i want the values from above function"
alert(url);
$.getJSON(url,function(json)
{
$.each(json,function(i,weed)
{
});
});
});
}

Related

scope of "this" changes when using grep in jquery widget

I have two groups of JSON data, one containing the data I want to filter down, and a second group representing the criteria for the filter.
The filter structure is pretty basic. It contains an Id of the element it's filtering on and it's value.
The other structure contains multiple fields, including the Id that relates back to the filter structure.
Both of these are stored in the global part of the widget. Normally, I would use this.filterData or this.jsonObjects to access them. However, if I try to filter using either grep, or the javascript array.filter function, then "this" changes, so I can't access the data anymore. Is there a way around this?
applyFilters: function() {
//var returnedData = $.grep(this.options.jsonObjects, this.grepFunction);
var returnedData = this.options.jsonObjects.filter(this.filterMatch);
filteredData = returnedData;
this.options.onFilterApply.call(this);
},
filterMatch: function(element) {
for(var key in this.filterData) {
if(this.filterData.hasOwnProperty(key)) {
for(var a = 0; a < this.filterData[key].values.length; a++) {
if(element[this.filterData[key].id]==this.filterData[key].values[a]) {
return true;
}
}
}
}
return false;
}
Hope this makes sense. During the applyFilters function, "this" represents the widget itself and it works fine. But as soon as it enters the filterMatch function, "this" becomes the window, so this.filterData is undefined. How can I access the filterData inside that function, or ultimately, what is the best way of filtering down a list of JSON objects?
You can save your scope in a variable before entering the filterMatch function.
Something like :
var that = this;
applyFilters: function() {
//var returnedData = $.grep(this.options.jsonObjects, this.grepFunction);
var returnedData = this.options.jsonObjects.filter(this.filterMatch);
filteredData = returnedData;
this.options.onFilterApply.call(this);
},
filterMatch: function(element) {
for(var key in that.filterData) {
if(that.filterData.hasOwnProperty(key)) {
for(var a = 0; a < that.filterData[key].values.length; a++) {
if(element[that.filterData[key].id]==that.filterData[key].values[a]) {
return true;
}
}
}
}
return false;
}
You can bind your this to the function scope also.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Outer Variable scope is not available inside the javascript function

How to access the outer variable inside the inner javascript function , please check my code below i need to access "index" variable inside app() function .
function validate()
{
for (index = 0; index < results.length; index++) {
var parsedData_1;
var provider = results[index].get("provider");
var user = results[index].get("user");
var addresses = user.get("addresses");
var address = addresses[1];
var GameScore = Parse.Object.extend("Address");
var query = new Parse.Query(GameScore);
var data = JSON.stringify(address);
var parsedData = jQuery.parseJSON(data);
query.get(parsedData.objectId, {
success: function(resultadr) {
var res = JSON.stringify(resultadr);
var parsedData_1 = jQuery.parseJSON(res);
var apartment = parsedData_1.apartment;
apa(apartment);
},
error: function(object, error) {
alert('error');
}
});
function apa(apartment)
{
alert(index); [I'm not getting the index value inside this function]
alert(apartment);
}
}
}
Inside the function apa() i need the index count , but im unable to get it , please help how to access the outer value inside the function.
As far as I can see apa() does not have access to the index variable, so I would put it inside the parameter of the function call, and call apa() like this
apa(apartment, index);
The problem is that you are using closures to access the index, thus the lastest value assinged to that variable is accessible in the app function. For example, if results.length equlas 11, index in app function will always be 11.
The soltion is to declare a variable inside the for loop, assign the index value to that variable, and pass the variable to app function.
//Create a factory function for the app function
//Outside the for loop.
var createAppFunc = function (i) {
return function () {
console.log(i);
};
};
for (var index = 0, l = results.length; index < l; index++)
{
var newVar = index;
var app = createAppFunc(index); //Now, app is a function.
}
Good Luck :).
You can use Function.bind() to pass the actual index as first argument to the sucess-callback. There you can get it and pass it along as parameter to function apa(). And: use keyword var for the index in for().
function validate() {
for (var index = 0; index < results.length; index++) {
/* all the vars here */
query.get(parsedData.objectId, {
success: function(idx, resultadr) {
var res = JSON.stringify(resultadr);
var parsedData_1 = jQuery.parseJSON(res);
var apartment = parsedData_1.apartment;
apa(idx, apartment);
}.bind(null, index),
error: function(object, error) {
alert('error');
}
});
function apa(index, apartment) {
console.log(index); console.log(apartment);
}
}
}
The first parameter (here: null) of bind() sets the context of the bound function. Whatever you pass in will be accessible in the success-callback by the keyword this.
I think every time you call the function the call will be compromised by next loop call.. so at last the method will be called only once.
You can declare index variable globally then all the functions have access to it

Passing objects to events jQuery

In this example I'm trying to iterate over the properties of an object that's passed to a click handler, but I am getting unexpected results.
Here's the fiddle
So with a JS script like
$(document).ready(function ()
{
Label = function (name, toDate, fromDate)
{
this.name = name;
this.toDate = toDate;
this.fromDate = fromDate;
}
lbl = new Label('John', 'Today', 'Yesterday');
$('#btnSubmit').click(function ()
{
for (var i in lbl)
{
console.log(i);
}
});
$('#btnSubmit2').click(function (Label)
{
for (var i in Label)
{
console.log(i);
}
});
});
Why can't I pass an object in the function of a click event and iterate over its properties instead of using the forin loop like I did in the btnSubmit example?
The callback is always called with the event as argument. When you write click(function(Label){ you only give that event variable the name Label (thus shadowing your outside constructor).
But you can access the variables defined in the outer scope, so what you want is probably
var lbl = new Label('John', 'Today', 'Yesterday');
$('#btnSubmit').click(function(){
for (var i in lbl) {
console.log(i, lbl[i]); // for example "name", "John"
}
});

variable closure using jQuery object notation

I have the following:
for (var i = 0; i <= 10; i += 1) {
var $page_button = $('<a>', {
html : i,
click : function () {
var index = i;
console.log(index);
return false;
}
});
$page_button.appendTo($wrapper);
}
I thought that var index would be defined separately for each iteration of the loop because it is enclosed within a function. In this case the value of index that is printed is always 10.
The link text is the correct value of i, because this is written to the DOM and is then immutable .
Why is this, and what should I change to fix my problem?
I know this is similar to lots of other questions but the behaviour of using this notation is causing a different result. I am using jQuery 1.7.2 (Can't use any newer unfortunately.)
You need to enclose that in a closure to solve the problem..
var $page_button = $('<a>', {
html : i,
click : (function (num) {
return function(){
var index = num;
console.log(index);
return false;
}
})(i)
});
A reference to i is closed up as part of the anonymous function. Note: not to its value, but a reference to i itself. When the function is run, the value is evaluated. Because the function runs after the loop has ended, the value will always be the last value of i. To pass just the value around, you do something like this:
click : (function (index) {
return function () {
console.log(index);
return false;
};
})(i)
You create an anonymous function which you execute immediately, which takes a value as argument and returns your actual function.
The variable index is defined separately for each execution of the function, but you copy the value from the variable i inside the function, so you will use the value of i as it is when the function runs, not when the function is created.
You need a function that is executed inside the loop to capture the value of the variable:
for (var i = 0; i <= 10; i += 1) {
(function(){
var index = i;
var $page_button = $('<a>', {
html : i,
click : function () {
console.log(index);
return false;
}
});
})();
$page_button.appendTo($wrapper);
}
Every handler is sharing the same i variable. Each one needs its own variable scope in order to reference a unique index.
for (var i = 0; i <= 10; i += 1) {
var $page_button = $('<a>', {
html : i,
click : makeHandler(i) // invoke makeHandler, which returns a function
});
$page_button.appendTo($wrapper);
}
function makeHandler(index) {
return function () {
console.log(index);
return false;
};
}
Here I made a makeHandler function that accepts the index argument, and returns a function that is used as the handler.
Because a function invocation sets up a new variable scope, and because a function is created and returned inside the makeHandler, each handler returned will reference its own scoped index number.

How to declare a global variable in Javascript using Jquery

Js file inside I have a function with a particular algorithm.
For reading xml file and transform the data to variable name wordData.
Inside the function has the following line of code:
var wordData = xhr.responseXML.getElementsByTagName (Node1);
I can not set the variable "wordData as a global" outside the function or global
Inside the function
function language() {
lang = "heb";
if (lang == "heb") {
thisWord = wordArrayHeb[indeXML];
}
else {
thisWord = wordArrayEng[indeXML];
}
alert("language thisWord:=" + thisWord);
}
function setWord() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var wordData = xhr.responseXML.getElementsByTagName(Node1);
XMLength = wordData.length;
for (i = 0; i < XMLength; i++) {
wordArrayHeb[i] = wordData[i].getElementsByTagName(Node2)[0].firstChild.nodeValue;
wordArrayEng[i] = wordData[i].getElementsByTagName(Node3)[0].firstChild.nodeValue;
}
language();
}
}
}
}
the variable thisWord is effected from varible wordData which is not global.
Outside the functions, varible thisWord is empty
inside the function is ok and it has a value.
Would love help.
Thank you!
Simply declare
var wordData;
outside the function and change your line to:
wordData = xhr.responseXML.getElementsByTagName (Node1);
Hence removing the var declaration.
You can create a global var anywhere in JS by using the window object:
window['wordData'] = xhr.responseXML.getElementsByTagName(Node1);
or
window.wordData = xhr.responseXML.getElementsByTagName(Node1);
Then wordData can be accessed globally. This may not be the best solution for your problem, consider using function arguments and return values instead.
i think setting it as a global var is not the best choice, if you wish to access wordData inside the function language, you should pass it as a parameter like so:
language(wordData);
and in declaring function language(), just make it so it accepts the parameter:
function language(wordData) {
...
}

Categories

Resources