I have something like the following:
$('#country1').change(function() {
var hrc = "Yes";
if (className == "HR") {
var hrc = "Yes";
return true;
} else {
var hrc = "No";
return false;
}
Then I am pulling this with JSON into a SP List like:
$('.submitdataAccounts').on('click', function() {
var data = {
__metadata: {
'type': 'SP.Data.ChangeOfAddressListListItem'
},
"high_risk_country": hrc,
};
This part works correctly as everything else in the form posts successfully into the list
If I leave it as a static variable at the top of the page it passes correctly but does not work if it's based on the fuction.
Thanks,
Declare the variable outside the functions, so it is a global variable, and then you can acces it everywhere in your code. If you give a global variable an another value, it is redefined and gets that value until an another value change.
Related
I have been working all day trying to pass the value of "returnData.salary" inside the "readData" function to
the object inside the "calculateTax" function which is suppose to take the salary value and calculate state and federal taxes. I am stumped, I can't find anything on the internet which provides a good example for me to work with. The examples are either way to simple or super complex. Any help would be appreciated.
I apologize in advance if I did not submit this question in the correct format. This is my first time asking for help on stackoverflow.
function readForm() {
var returnData = {};
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
$("#name2").text(returnData.name);
$("#lastName2").text(returnData.lastName);
$("#age2").text(returnData.age);
$("#gender2").text(returnData.gender);
$("#salary2").text(returnData.salary);
$("#myTextArea2").text(returnData.myTextArea);
if ($(isManager).is(':checked')) {
$("#isManager2").text("Yes");
}
else {
$("#isManager2").text("No");
}
//$("#employeeForm")[0].reset();
} //end of readForm function
function calculateTax() {
console.log("Button Works");
var calculateTax = {
state: function(num) {
num *= 0.09;
return num;
}
, federal: function(num) {
if (num > 10000) {
num *= 0.2;
return num;
}
else {
num * 0.1;
return num;
}
}
, exempt: true
};
}
//Invoke readForm function when the submit button is clicked.
$(document).ready(function () {
$("#btnSubmit").on("click", readForm);
$("#btnCalculate").on("click", calculateTax);
})
</script>
Well, simply put; you can't. Not like this anyway. Or, at least not pass the value to the function directly.
You are using global functions right now, which are not inside a class. If it was inside a class, you could instantiate the class and save it to this (which would be the class' instance). However, I'm assuming classes are a bit over complicated in this case. What you could do, is set variables globally so all functions can use them, like this;
//declare the global variable so it exists for every function
var returnData = {};
function readForm() {
//We do NOT redeclare the "var" again. It's global now.
returnData = {}; //Reset the global variable when this function is called
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
//Rest of your function
}
function calculateTax(){
console.log(returnData) //works here
}
Note that you do overwrite global variables, so it's best to reset them on every function call. You might get old data stuck in there, otherwise.
What am I doing wrong, and how can one pass variables to a different function within the same wrapping variable/function.
Example:
function customFunctionWrap(){
this.myVar1 = 0;
this.getCurrentPosition = function(){
if (navigation.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){});
}
},
this.doSomething = function(){ // Works
//Do something, return
this.callWithParams(); //Works
},
//If I remove passing in 'value1',calling it elsewhere works
this.doSomethingWithParams = function(value1){
//Use value1
//Return
},
this.callWithParams = function(){
var value1 = 'xyz'; //Is a variable that changes based on some DOM element values and is a dynamic DOM element
this.doSomethingWithParams(value1); //THROWS TYPEDEF ERROR: this.doSomethingWithParams is not a function
this.getCurrentPosition();
}
};
var local = new customFunctionWrap();
local.doSomething(); //WORKS
I know there is another way to do it and then directly use customFunctionWrap.callWithParams(), but am trying to understand why the former approach is erroring out.
var customFunctionWrap = {
myVar1 : 0,
callWithParams : function(){
}
}
What JS sees:
var customFunctionWrap = (some function)()
returned function is fired, because the last (), so it has to yield/return something, otherwise, like in your code it is "returning" undefined.
So your given code does not work.
The very first fix is to delete last 2 characters from
var customFunctionWrap = (some function)()
to make it return constructor.
Is it possible to access an object inside another if statement? Because the situation is like this.
I have an edit button and it will set a <div> to contenteditable. so if I press the cancel button, the text inside the <div> should also reset. and now my javascript goes like this
$('.class').on('click','.etc',function(){
var orig = {};
$a = $(this).('.etc').text().trim(); // just getting the text of the button
if($a == "Edit") // just checking if edit button
{
orig.text = $(this).find('original-text').text(); // should store the original text
}
else if ($a == "Cancel")
{
// the div must be set to the original text
alert(orig.text); // undefined
}
});
I'm really at lost here
Declare the variable at a scope where it is accessible by both the if and the else condition or maybe at a global scope. But make sure it's initialized before you try to access its properties!
var orig = {text:""};
$('.class').on('click','.etc',function(){
if($a == "Edit") // just checking if edit button
{
orig.text = $(this).find('original-text').text();
}
else if ($a == "Cancel")
{
alert(orig.text);
}
});
The issue is in the scope of the variable orig. JS has function level lexical scope.
So to answer your title question, yes you can access a variable created in an in in if in the else so long as the else is sure to occur after the if has occurred at least once. But that's not really what's causing your problems.
Your issue is that you are trying to persist this variable beyond the onclick function. When that function ends so does the life of the variable. The simple fix is to declare it outside the function and utilize JS closures.
var orig = {};
$('.class').on('click', function () {
if ($(this).text() == "Store") {
orig.text = $("#display").text();
} else if ($(this).text() == "Cancel") {
alert(orig.text);
}
});
I had to adapt it a bit because I don't know your full HTML, but it works.
UPDATE
To avoid the bad practice of global variables you can create a closed scope for the whole thing like so:
(function () {
var orig = {};
$('.class').on('click', function () {
if ($(this).text() == "Store") {
orig.text = $("#display").text();
} else if ($(this).text() == "Cancel") {
alert(orig.text);
}
});
})();
And here's that in practice
I have a global variable NS which I can access from the console as such:
NS.some_func();
NS is populated using a method called extendSafe()
some_scope.extendSafe = function (o1, o2) {
var key;
for (key in o2) {
if (o2.hasOwnProperty(key) && o1.hasOwnProperty(key)) {
throw "naming collision: " + key;
}
o1[key] = o2[key];
}
return o1;
};
This is used by setting up a public scope called $P and then copying over to the global scope NS once all the $P methods have been defined.
I want to to it this way so I can verify that I'm not writing over any properties.
This worked well until I tried to save a local variable to $P for later copying to NS. Because the interpreter does not know that $P will be "released" to the window scope, it does not know to keep the local variable active. So I can not use my safeExtend method.
I verified this was the issue by doing a direct copy as such:
NS.local = local;
I can now access NS.local from the console.
However if I copy it over as I wish to do:
$P.local = local;
extendSafe(NS, $P);
The local variable is not available.
How can I safely release it, i.e. using safeExtend()?
Code Snippet
Issue is commented as
// hacked needs a fix
$P.machine = function (obj) {
var pipe,
data_send,
ajax_type,
wait_animation,
set;
wait_animation = document.getElementById('wait_animation');
set = false;
pipe = NS.makePipe(obj);
if ($R.Parsel[pipe.model] === undefined) {
return;
}
time('start');
if ($R.Parsel[pipe.model].hasOwnProperty("pre")) {
pipe = $R.Parsel[pipe.model].pre(pipe);
} else {
return;
}
if (pipe.form_data) {
ajax_type = 'multi';
var form_data = pipe.form_data;
delete pipe.form_data;
form_data.append("pipe", JSON.stringify(pipe));
data_send = form_data;
} else {
ajax_type = 'post';
data_send = 'pipe=' + encodeURIComponent(JSON.stringify(pipe));
}
if (pipe.state === true) {
time('middle');
if (wait_animation) {
set = true;
wait_animation.style.opacity = 1;
}
NS.ajax({
type: ajax_type,
url: NS.Reg.get('path') + NS.Reg.get('path_ajax'),
data: data_send,
callback: function (pipe_string_receive) {
var pass_prefix = pipe_string_receive.slice(0, 3),
times;
if (wait_animation && set) {
wait_animation.style.opacity = 0;
}
if (pass_prefix === '|D|') {
NS.log('|DEBUG| ' + pipe_string_receive.slice(3));
} else if (pass_prefix === '|A|') {
time('middle');
pipe = JSON.parse(pipe_string_receive.slice(3));
if ($R.Parsel[pipe.model].hasOwnProperty("post")) {
pipe = $R.Parsel[pipe.model].post(pipe);
times = time('finish');
pipe.time.pre = times[0];
pipe.time.transit = times[1];
pipe.time.post = times[2];
// works but hacked needs a fix
NS.last = pipe;
// will not exendSafe()
$P.last = pipe;
} else {
return;
}
} else {
throw "<No 'A' or 'D'>" + pipe_string_receive;
}
}
});
}
};
I see you've solved the problem, but I have a feeling that there's something you're misunderstanding about JavaScript:
This worked well until I tried to save a local variable to $P for later copying to NS. Because the interpreter does not know that $P will be "released" to the window scope, it does not know to keep the local variable active. So I can not use my safeExtend method.
I verified this was the issue by doing a direct copy as such:
NS.local = local;
I can now access NS.local from the console.
However if I copy it over as I wish to do:
$P.local = local;
extendSafe(NS, $P);
The local variable is not available.
How can I safely release it, i.e. using safeExtend()?
This doesn't make sense. JavaScript is very good at keeping track of references to objects. If there are any references to an object, it won't garbage collect the object. I have no idea what it could mean to "release an object to the window scope". There isn't really any such concept, just objects and references to them.
I tried looking through your original code, but there's a lot of code there that isn't related to the problem. If you were to simplify it to a minimal test case, I'll bet a simpler solution would become evident.
I do see one issue in your smaller snippet above. You defined your extendSafe() function as some_scope.extendSafe(), but here you're calling it with a plain extendSafe() call and no reference to some_scope. Did it actually call the function? Is this just a typo in the smaller example?
Of course, if you're just happy to have found a solution and want to move on, that's quite understandable! I just have a strong feeling that there's extra code here that you don't need.
I'm using dajaxice to retrieve a json attribute - that I would like to be global. I'm not sure why my global var is always "undefined":
var recent_id;
$(function(){
recent_id = Dajaxice.ticker.get_home_timeline(get_home_timeline_callback);
alert(recent_id);
});
function get_home_timeline_callback(data){
if(data==Dajaxice.EXCEPTION){
alert('Error! Something happens!');
}else{
var parsed = JSON.parse(data.home_timeline);
var parsed_id = {'parsed_id':parsed[0].id_str};
console.log(parsed_id);
}
return parsed_id;
}
#dajaxice_register
def get_home_timeline(request):
home_timeline = oauth_req(
'http://api.twitter.com/1/statuses/home_timeline.json?count=1',
settings.TWITTER_TOKEN_KEY,
settings.TWITTER_TOKEN_SECRET
)
return simplejson.dumps({'home_timeline': home_timeline })
Is this a bad way to access a var to be used in another ajax function?
Seems like async issue. Modify your get_home_timeline_callback function as following
function get_home_timeline_callback(data){
if(data==Dajaxice.EXCEPTION){
alert('Error! Something happens!');
}else{
var parsed = JSON.parse(data.home_timeline);
var parsed_id = {'parsed_id':parsed[0].id_str};
console.log(parsed_id);
}
//debug
alert(parsed_id);
//since the value has come, now assign it to the global variable
recent_id = parsed_id;
}
It seems like the variable scope issue. The scope of the variable parsed_id is declared within the else statement within the { }, so its scope is within the else statement. And when you return the parsed_id outside the brackets it might be giving undefined.
Go through the scope of variables explanation here
Change your function as shown below.
function get_home_timeline_callback(data)
{
var parsed_id = "";
if(data==Dajaxice.EXCEPTION)
{
alert('Error! Something happens!');
}
else
{
var parsed = JSON.parse(data.home_timeline);
parsed_id = {'parsed_id':parsed[0].id_str};
console.log(parsed_id);
}
return parsed_id;
}
Now here the scope of the variable parsed_id can be accessed anywhere within function.
Hope this solves your problem if not sorry. This was my assumption that the scope might be affected.