how to get a variable over to a function? - javascript

i want to get a variable (which is set when a link is clicked) over to a function and show it as a pop out.
the code as shown below:
$('a#link1').click(function(e){
e.preventDefault();
var value = 'true';
});
function exe(){
alert(value);
}
when the function is executed , all i get is value is undentified.
So anyone knows a way around it?

Variables have scope, you define the value variable in the scope of the onclick closure, and it wont be accessible outside it.
The following would work:
var value = false; //Define in the global scope
$('a#link1').click(function(e){
e.preventDefault();
value = false; //Use in a local-scope is legal.
});
function doSomething()
{
alert(value);
}
However having many global variables will make your project hard to maintain, and there are other more clean solutions available. In general i'd recommend you to read a proper book on programming though :)

Just make the variable global, or better yet "attach" it to the element using the .data():
$('a#link1').click(function(e) {
e.preventDefault();
$(this).data("value", "true");
});
Then you can always check for this:
function exe() {
alert($('a#link1').data("value"));
}
Note that it was added in jQuery 1.2.3 guess that by now it doesn't really matter though.

Related

Passing Scope Through $(document).ready

Can someone explain to me why this doesn't work and show me how to make it work? I've tried creating a namespace and IIFEs functions but I cannot seem to get it.
$(document).ready(function() {
alert (hi);
});
$(document).ready(function() {
var hi = "hello"
});
Thank You!
When you do this:
$(document).ready(function() {
var hi = "hello"
});
You are creating a variable named hi that is local to that callback function. It is simply not accessible outside that function. This is a feature of the language.
You can declare the variable at a higher scope like this:
var hi;
$(document).ready(function() {
hi = "hello"
});
And, then the value of that variable will be available outside the scope, but you will not necessarily know when it gets the proper value because you won't know when the $(document).ready() callback is called unless you put your code inside that callback.
It really makes little sense to try to share a variable between two calls to $(document).ready(). It would make much more sense to just put the code inside the same $(document).ready() callback:
$(document).ready(function() {
var hi = "hello"
alert (hi);
});
Not Really Recommended
If you were going to try to share a variable between two calls to $(document).ready() (something I don't really recommend because it makes your code somewhat fragile), it can be done. Callbacks to $(document).ready() will be called in the order they are attached so you will have to order things appropriately:
var hi;
$(document).ready(function() {
hi = "hello"
});
$(document).ready(function() {
alert (hi);
});
This will make sure that the first $(document).ready() callback that sets the value of hi will be called first before the second one where you try to use the value.

Alternative to global variables in javascript/jquery?

So, I've got my app to work. But I don't want to use a global variable.
Here's what I'm trying to do:
var AMLid;
$(".commentButton").on('click', function () {
AMLid = $(this).closest('tr').siblings().find('p.important').text();
alert("id is:" + AMLid);
});
$(".saveButton").on("click", function () {
$(".modal-body #txtAddComment").val(AMLid);
});
I want to get an ID from a selected table row, and pass the ID to the modal dialog, so I then can use the ID as a parameter when clicking a button in the modal dialog.
How do I do the exact same thing, without using a global variable? is it possible?
And what are the cons of using a global variable like this? Does it crash or target the wrong ID's if many people use it simultaneously?
Any help is appreciated.
You can wrap the whole thing in a function
(function(){
var AMLid;
$(".commentButton").on('click', function () {
AMLid = $(this).closest('tr').siblings().find('p.important').text();
alert("id is:" + AMLid);
});
$(".saveButton").on("click", function () {
$(".modal-body #txtAddComment").val(AMLid);
});
})();
You can avoid the use of a global variable by using an Immediately-Invoked Functon Expression, which would look like this:
(function() {
var AMLid;
$(".commentButton").on('click', function () {
AMLid = $(this).closest('tr').siblings().find('p.important').text();
alert("id is:" + AMLid);
});
$(".saveButton").on("click", function () {
$(".modal-body #txtAddComment").val(AMLid);
});
})();
This works because the AMLid is now private to the function; when the function is executed it creates a new execution context which includes that variable, which is then accessible to statements made in the function, but not outside it. And because this creates a closure the variable continues to be accessible by the callbacks attached to those functions. Moreover, as the function is anonymous it itself doesn't have a name polluting the namespace.
The term Immediately-Invoked Functon Expression comes from Ben Alman, and you can read his original blog post discussing the concept here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Some cons of using a global include: hard to keep track of variables, other scripts might mess with its value (when they probably shouldn't have access to it), harder to maintain, less clean code. Your worry about it being overwritten if multiple people use it won't be an issue because it's client-side and so there will be one instance per page loaded in any given browser.
Javascript is client-side so actually I can't get the point in your "many people use it simultaneously". One browser for user, so you don't have to worry about multiple client. Each one use his own set of global variable.
If your executions are not linked in any way (they are "onclick") you can just wrap them in a function so you're actually setting a "local/global" variable.
Every function that'll need that AMLid has to be declared inside that function scope.
The only way to keep variables out of the global scope is by wrapping them in a function. If this is all the code you're using in this particular module, it doesn't really make a difference.

Use JavaScript value from jquery to javaScript function

I want to get a value stored in a variable Get_Current_id in a jquery clicked function and use in a javascript PrintContent(). Any help would be appreciated.
jQuery:
$('#AgeGroupWiseButton').click(function()
{
var Get_Current_id = $('#AgeGroupWiseButton').val();
});
js:
<script>
function PrintContent()
{
alert(Get_Current_id );
}
</script>
Remove the var. Otherwise, it's scoped to the current function and inaccessible outside of it.
Ideally, you should have these two functions in a closure of their own, but global variables will work too.
Declare Get_Current_id outside of the jquery event handler makes it accessible to other functions. Note that Niet the Dark Absol's suggestion to just remove the var from inside the jquery event handler is bad practice as it creates an implied global (which can create confusing problems).
var Get_Current_id;
$('#AgeGroupWiseButton').click(function()
{
Get_Current_id = $(this).val(); // no need to re-select
});
function PrintContent()
{
alert(Get_Current_id );
}

Javascript Problems using Global variables within anonymous functions

$(document).on({ready : iniciarjquery});
var validaciondeZona = true;
function iniciarjquery(){
$('#AgregarDestinoTuristico').on('keyup', '#Zona2', function(e) {
alert(validaciondeZona); // undifined
});
}
Please help me, I need to use the validaciondeZona boolean variable as a global variable, but I define the variable outside the function iniciarquery and try to use the variable within the function and global and everything works fine throws me the value assigned outside the function iniciarquery.
But the problem is when I want to use a function within an event happens anonymous when I try to use the variable and the value undifined throws me.
I already tried with:
window.validaciondeZona,
also with window ['validaciondeZona'],
also with root ['validaciondeZona']
and also with this.validaciondeZona.
Please help, how I can I use that global variable inside that anonymous function and modify, please
$(document).on({ready : iniciarjquery});
var validaciondeZona = true;
function iniciarjquery(){
alert(validaciondeZona); // true
}
I tried it with:
$(document).ready(iniciarjquery);
And it is exactly the same. I do not know what else can be done.
This doesn't seem to work :
$(document).on({ready : iniciarjquery});
FIDDLE
change to
$(document).ready(iniciarjquery);
FIDDLE

Ajax returned variable issue

I am trying to assign the ajax callback function variable value to the existing variable.
I have
function test(){
}
test.prototype.click=function(){
this.count;
//call ajax codes.....
//ajax callback function
ajax.callback=function(var1){
//I want to assign returned data to this.count property.
this.count=var1.length
}
}
test.prototype.show=function(){
//wont work, it will show undefined...
alert(this.count);
}
var t=new test();
t.click();
t.show();
I think it's the scope issue but I don't know how to solve this. Any idea? Thanks in advance.
Yeah, using this within another scope causes all kinds of issues, so you need to work around this. One way is to avoid using this entirely by defining your function differently. For instance, you can define count like so:
function test() {
function count() {
}
...
And just use count() without the this. prefix.
You can also set a variable to this and use that to refer to count within your other scope. For instance:
var self = this;
Scoping issues with this can be a pain in the neck and can occur when you do more OO with callbacks. It's good you got introduced to this early on, so now you know to be on guard.

Categories

Resources