How to get a variable value from a javascript function - javascript

I am trying to get a variable from a javascript function, but I am having a problem getting it the variable value outside the function. The variable value can be outputted just fine inside the function. Here is the script, but how can I get the value of status and use it outside the funcion?
<script>
function get_id(){
$('.addressClick').click(function() {
var status = $(this).attr('id');
alert(status); // Here the value is printed correctly
return status;
});
}
var variable = get_id();
alert(variable); // Here the valiable isn't outputed
$("#"+variable).confirm();
</script>

You can't do this, see my example :
function get_id(){
$('.addressClick').click(function() {
//...
});
return 12;
}
var variable = get_id();
alert(variable); //12
'return status;' is in event function and not in get_id function.
The solution is that (don't use global variable if you have big project) :
$('.addressClick').click(function() {
$('.statusSelected').removeClass('statusSelected');
$(this).addClass('statusSelected');
});
alert($('.statusSelected').attr('id'));
$("#"+variable).confirm();

Related

Passing variable that detects specific button in jQuery

I created function that recognize which post has been clicked on.
jQuery(document).ready(function() {
jQuery(.recognize-post).on("click", function() {
var clickedButton = jQuery(this).data("id")
console.log("click button with post id: ", clickedButton)
button-id = "recognize-post"
...
...
})
})
}
html
<button id="recognize-post" class="recognize-post" data-id="<?php the_title() ?>">POST</button>
Code above works perfectly and in recognizes the correct post, but I need to pass clickedButton outside of this function and I don't know how to do so.
I need to have it in else if function, this is my attempt
else () {
...
} else if (button-id === "recognize-post") {
console.log(clickedButton)
}
Here the problem comes, clickedButton is underfined and need it to recognize post in exactly the same way how in on click function. Is it possible?
You can make a separate function that takes in the information you want to preserve.
// make a new function
function doSomethingWithTheIdAndBtn(id, btn) {
// take in arguments that represent the id or btn or whatever you need
else () {
...
} else if (id === "recognize-post") {
console.log(btn)
}
}
jQuery(document).ready(function() {
jQuery(.recognize-post).on("click", function() {
var clickedButton = jQuery(this).data("id")
console.log("click button with post id: ", clickedButton)
button-id = "recognize-post"
doSomethingWithTheIdAndBtn(button-id, clickedBtn) // call the function
...
...
})
})
}
So, the issue here is that if you declare a variable function in a given "scope" — in your case, the anonymous function's scope — it will only be defined inside of that scope. If you want to use the variable outside of the function, you need to declare it outside of the function.
So, for instance, if your code was
function foo() {
var myVariable = 0;
}
foo();
// This will throw an error, cuz myVariable is not defined in this scope
console.log(myVariable);
you could fix it by declaring the variable outside of the function's scope
var myVariable; // declare it outside of the function
function foo() {
myVariable = 0; // give it a value inside of the function
}
foo(); // call foo so that myVariable has a value
console.log(myVariable); // this will print 0. Success!

How to make a js var in a function global to use it outside?

I want to make the "var id" in the function global. That i can use the value of it in the alert outside the function. Thats my code:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
}
alert(id);
</script>
You didn't specified what is your final goal or why are you trying to move id to a global scope, but you can do it by simple moving the var id (declaration) outside the function, then it will be global and accessible by all functions.
Obviously, the alert will show "undefined" since id only gets some value when the myFunctionGetCode() is called.
The code below shows this.
var id;
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
id = con+code;
console.log(id)
}
alert(id);
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
BUT if you want to throw the alert with the id value only when it gets some value then you should move the alert() inside the function. (You can still declare the id variable outside the function to let it global, or inside the function, as you currently have)
Open snippet to see:
//var id; -> You can still declare it here (as global)
function myFunctionGetCode() {
var code = getInputVal('code');
var con = "/";
var id = con+code; //or you can declare it here, but not global
alert(id);
}
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
From your sample code I guess that you do not want to make your value global, but that you want to return a value - after all you are doing an operation inside your function that calculates a value from certain inputs.
So you would use the return keyword, and call the function to get the value:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
return id;
}
alert(myFunctionGetCode());
</script>
As a rule you do not want to make function variables global, since this means the value can be changed anywhere in your script or website, and that might lead to side effects and unexpected values in your function. If you need to pass something in use function parameters (or read from a text input like in your case), if you want to give back a result use return.
Can you move the alert inside the function or return the "id" value from the function instead?
You can make the variable global by doing something like:
window.your_namespace.id = value;
and then access the variable in the same way:
value = window.your_namespace.id
but its best not to pass data around using the global namespace.
You have to make var id to property of window object then you can access the id out side the function.
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
window.id = 10;// Change to this
}
myFunctionGetCode();
alert(id);

Global variable in javascript result is always undefine

I had trouble with my global variable hope you can help me.
<li>
Add Question
</li>
Now from that line I passed my id in this line by click() in javascript
$(document).ready(function () {
var correctAnswer;
var subId;
$( ".subject" ).click(function() {
subId = ($(this).attr('id')); //passed the id variable into the global variable
alert(subId) // when I alert this it returns the value
});
now I used the global variable in this line the same $(document).ready(function ()
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
var correct = correctAnswer;
var passedSubId = subId; // passed the global variable to this local variable
console.log(correct); // this is okey
console.log(subId); // this is undefined
});
result
i
undefined
You can use window to declare a global variable though it is highly recommended not to use.
You can declare a global variable like this:
window.yourVariable = "something";
Your code will never work as you think it will.
What you are doing there I think is you click on your link, which then moves you from page A to page B, and you want to use that variable that you set on page A on page B, sorry but this will never work, when you refresh your page your entire script is run again and it does not know what have you done on the previous page.
You would have to either take that id from the url ( its there ) or store it for example in local storage, try this:
$(document).ready(function () {
var correctAnswer;
var subId;
$( ".subject" ).click(function() {
subId = ($(this).attr('id')); //passed the id variable into the global variable
alert(subId) // when I alert this it returns the value
localStorage.setItem('subId', subId);
console.log('id stored');
});
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
var correct = correctAnswer;
var passedSubId = subId; // passed the global variable to this local variable
console.log(correct); // this is okey
console.log(subId); // this is undefined
storedSubId = localStorage.getItem('subId');
alert(storedSubId);
console.log('stored id');
});
});
Anyway getting it from url is definitely the way you want to go

can't get jqPlot chart to show line from Variable

I'm using jqPlot to plot some points in my webApp, so I'm trying this:
var plot10 = $.jqplot ('heightChartDiv', [[3,7,9,1,5,3,8,2,5]]);
and it works fine, I this exact chart here
but when I take it out, to give it a value, like so:
$(document).ready(function(){
var serie1 = [[3,7,9,1,5,3,8,2,5]];
}
function doGraph(){
var plot10 = $.jqplot ('heightChartDiv', serie1);
}
It doesn't work. am I declaring the variable wrong? please HELP!
~Myy
Your variable scoping is all off. The variable serie1 has local scope to the anonymous function defined in $(document).ready event. Read up on javascript scope here and here.
Perhaps something like this:
// the document ready will fire when the page is finished rendering
// inline javascript as you've done with your doGraph will fire as the page renders
$(document).ready(function(){
// first define graph function
// make the series an argument to the function
doGraph = function(someSeries){
var plot10 = $.jqplot ('heightChartDiv', someSeries);
}
// now call the function with the variable
var serie1 = [[3,7,9,1,5,3,8,2,5]];
doGraph(serie1);
}
EDITS IN RESPONSE TO COMMENT
See this below example:
$(document).ready(function(){
var a = 1;
someFunc = function(){
var b = 2;
alert(a);
}
someFunc(); // this works
alert(b); // this produces an error
});​
Here the variable a is considered global to the function someFunc. A variable declared in someFunc, though, does not persist outside of it.

Is it not a right way to call my obj function?

I have a function which is return a object. in the object i have two function to show the popup and close it. it works within the parent function, but it's not from out side.. is it not a right way to call that.. else how can i call the obj function from out side?
my function :
var popupHandler = function(handler,msg,popUp){
msg = msg == "help" ? "help" : "results"
$(handler).click(function(){
popObj.showPop(); //works
})
$('.cls-how2play').click(function(){
if(msg == 'help') popObj.closePop(); //works
});
var popObj = {
showPop : function(){
if(!(popUp).is(':visible')) $(popUp).fadeIn().children().find('.'+msg).show().siblings().hide();
},
closePop : function(){
$(popUp).fadeOut()
}
}
return popObj;
}
from calling ouside like this :
$('.ui-footer').click( function(){
var closeIt = popupHandler();
closeIt.popObj.closePop() }) //not works.. why?
}
any one can help me the right way to call the obj functions from outside of the returning function?
thanks.
Rather than
closeIt.popObj.closePop()
You want
closeIt.closePop()
Your popupHandler function returns the popObj object, which has the showPop and closePop functions on it. So closeIt is a reference to that same object.
As you are returning the popObj, your closeId will get only the two functions, not wrapped in the popObj object. Therefor you will call the function like so, without popObj:
closeIt.closePop();
There is no need to wrap this in an object since you immediately return it.
you can write
return{
showPop : function(){
if(!(popUp).is(':visible')) $(popUp).fadeIn().children().find('.'+msg).show().siblings().hide();
},
closePop : function(){
$(popUp).fadeOut()
}
}
Now closeIt.closePop(); should work very well.
As i can c
popupHandler is a function, and popObj is a return result of the function "popupHandler"
when the program run to
var closeIt = popupHandler();
it means that the "closeIt" assigned by the result of the function "popupHandler", a obj as the same as the "popObj".
you can consider that "closeIt" is a copy of "popObj".
and "popObj" is not a property of "closeIt" , them are the same.
so you should code closeIt.closePop(), but not closeIt.popObj.closePop(),
and not popObj.closePop() as well.
because popObj was "var"ed in the declare of the popupHandler, it belonged that scope.
You should just call:
closeIt.closePop();

Categories

Resources