Jquery - Grab Variable from Another Function - javascript

I have two functions on my page. I am trying to find a way to access a variable in function 1 inside function 2:
$(function() {
$('a[id=1]').live("click", function(event) {
event.preventDefault();
var Var1 = "something1";
});
});
$(function() {
$('a[id=2]').live("click", function(event) {
event.preventDefault();
var Var2 = event.var1;
});
});
So I am sure my above is incorrect but you can see how in function 2 I am trying to grab a variable from the first function.
Is there a way I can do this? I don't know why, but I keep thinking it has something to do with the event.var1 or the event functionality.

You need to declare the variable outside both functions, in a scope they can both access. I suggest combining your two document ready handlers into a single function and declaring the variable there:
$(function() {
var var1; // may want to assign a default
$('a[id=1]').live("click", function(event) {
event.preventDefault();
var1 = "something1";
});
$('a[id=2]').live("click", function(event) {
event.preventDefault();
var var2 = var1;
});
});
Or you could make the variable a global if you need to access it from other places too.
Note that the two click events have nothing to do with each other so they certainly don't share event data. Also, a click on the second anchor may occur before a click on the first, so you may want to give var1 a default value and/or test for undefined befor using it inside the second click handler.
(Also I've changed Var1 to var1 because the JS convention is to start variable names with a lowercase letter - you don't have to follow the convention, but I'd recommend it.)

Each event are will be unique from each click, you can store your result in a global variable in the window object and take care of the order of the events
$(function() {
$('a[id=1]').on("click", function(event) {
event.preventDefault();
window.Var1 = "something1";
});
});
$(function() {
$('a[id=2]').on("click", function(event) {
event.preventDefault();
var Var2 = window.Var1;
});
});

Related

getting the element's id from on click with (this)

To initiate the onclick event, I have this
[].forEach.call(btnAddVendorDropDown, (btnAddVendorDropDown) => {
btnAddVendorDropDown.addEventListener('click', onAddVendorDropDownClick, false);
});
The function is
function onAddVendorDropDownClick(e) {
e.preventDefault();
addNewClass(modal, 'is-active');
addNewClass(modalAddVendorDropDown, 'is-active');
const test = $(this).attr('id');
console.log(test);
return test;
}
So what I'm trying to do is when a user clicks btnAddVendorDropDown, the function onAddVendorDropDownClick is called. I need to grab the id from the element. When I do console.log of the element attribute id from inside the function, I get exactly what I need. The problem I'm running into is when I try to grab it from outside the function, I keep getting undefined. I don't understand how I can grab the id once it calls this function from outside this function.
I tried this
var num = onAddVendorDropDownClick();
console.log("the function return is " + num);
Which is what shows undefined.
this is related directly to the caller's scope. This means that without "binding" a scope to your event handler, this is going to refer to your main application scope, and not the scope that jquery passes as you chain functions.
You can either wrap the event object's target:
function onClickHandler(e) {
$(e.target).attr('id');
}
Or you can use $(this) within the jquery context of a click handler:
$('#my-button').on('click', function(e) {
$(this).attr('id');
});
The last example works because it is occurring inside a JQuery closure, so it retains the scope from the previous function. Outside of a closure, this means something else.
$(this) is JQuery context, and you are inside javascript function. You can change the click button to JQuery to use it:
var test;
$("button").click(function(){
test = $(this).attr('id');
console.log(test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnTeste">
Teste
</button>

How to pass `$(this)` as parameter to a "callready" function in Javascript

The leanModal function triggers a modal with some parameters. One of this parameters is a function (ready) that will be executed once the Modal is open. The point is, I need to do some stuff inside that function (ready) just with the element (tag) which triggered the modal, so I need to pass $(this) as parameter to that function. The leanModal() function is provided by MaterializeCss which's the framework that I'm using.
I've been trying this, but thisTag is always undefined. I also have tried to pass directly $(this) to the function, but it also doesn't work at all, it's still undefined. So, how can I reach this?
$('.modal-trigger-editMedic').leanModal({
thisTag: $(this),
ready: function(thisTag){
var refereeNum = thisTag.siblings("[name*='refereeNumToEdit']" )[0].value;
$('#surname').val($("input[id*='medicNameToModal"+refereeNum+"'").val());
}
});
Following the source code, .leanModal supports a ready function (which is triggered once the modal is visible) but doesn't bind or send the element which triggered the modal, the easiest way to fix this is to store a reference outside. To do so, you need to iterate over the triggers yourself instead of relying on that functionality of provided by this jQuery plugin.
Like so:
var $surname = $('#surname'); // you should store the selector as a reference
// outside the loop for better performance
$('.modal-trigger-editMedic').each(function() {
var $this = $(this); // this is the current item in the set of elements,
// therefore our trigger element
// EDIT: using var makes this a local variable
$this.leanModal({
ready: function() {
var refereeNum = $this.siblings("[name*='refereeNumToEdit']" )[0].value;
$surname.val($("input[id*='medicNameToModal"+refereeNum+"'").val());
}
});
});
When you are inside the leanModal it becomes this. Try setting a var to $(this) and pass that through.
var that = $(this);
$('.modal-trigger-editMedic').leanModal({
thisTag: that,
ready: function(thisTag){
var refereeNum = thisTag.siblings("[name*='refereeNumToEdit']" )[0].value;
$('#surname').val($("input[id*='medicNameToModal"+refereeNum+"'").val());
}
});

How to use the same variable in two different jQuery events?

I am working on a rating system and want to pull up each rating value by the jquery.
For this purpose I am doing like this, but I am unable to get previous event variable value into next event.
var r1Rating;
$(".rating-input").on("click",function(){
//alert($(this).attr("id"));
var r1=$(this).attr("id");
var r1Array=r1.split("-");
//alert(r1Array[r1Array.length-1]);
var r1Rating=parseInt(r1Array[r1Array.length-1]).toFixed(2);
$("#total_rating").html(r1Rating);
var r1Rating=r1Rating;
});
$(".rating-input1").on("click",function(){
alert(r1Rating); //I want to get value here
});
Any help, suggestion would be appreciated. Thanks
Even though you have a r1Rating in the external scope, since you are using var r1Rating in the click handler, you are creating a new locally scoped variable in the click handler. So any changes you make to the variable will be visible inside that method only and the variable in the external scope will not be updated.
var r1Rating;
$(".rating-input").on("click", function () {
//alert($(this).attr("id"));
var r1 = $(this).attr("id");
var r1Array = r1.split("-");
//should not use var here
r1Rating = parseInt(r1Array[r1Array.length - 1]).toFixed(2);
$("#total_rating").html(r1Rating);
});
$(".rating-input1").on("click", function () {
alert(r1Rating); //I want to get value here
});
The code below should be changes, since in this instance, you created a new r1Rating variable in a scope, which means that this was a different variable from the global one outside.
var r1Rating=r1Rating;
This should be changed to:
r1Rating=r1Rating;

JQuery change variable value outside the function

I want to change the value of my "clients" variable from outside the function, with the one from inside the function(which changes when I select something), and I dont know how to do that. Please help
This is my code code
<script>
var clients;
$('#clients').on('change',function(e)
{
console.log(e);
var clients = e.target.value;
});
document.write(clients);
</script>
var keyword creates a local variable. Remove it to have access to variable from the outer scope:
var clients;
$('#clients').on('change', function(e) {
clients = e.target.value;
});
However, you should keep in mind that alert(clients) in your last line will always display undefined as the change event will be triggered later when the actual event will fire.
by using var inside the function you're redefining it in that scope, just remove var inside the function
var clients;
$('#clients').on('change',function(e)
{
console.log(e);
clients = e.target.value;
});
alert(clients);

Cache a variable exclusively on a function

Is there a way to cache a global variable for a function within a group of functions, without calling that function directly from another?
For example, if I have a group of functions wrapped in a parent function like this:
function parentFunction() {
var myVariable;
someDiv.addEventListener('click', function (e) {
myVariable = e.target;
});
anotherDiv.addEventListener('click', function (e) {
// use myVariable without it changing when the above is fired again.
});
}
The global variable is declared at the start, it is given a value in the first function, which carries over to the second for use.
But how can I stop it from continually updating in the second function, if the first function fires again?
Could I add another event-listener inside the second function to check if the first fires again and ensure the variable doesn't change?
You can set the variable only once in the first function:
someDiv.addEventListener('click', function (e) {
if (!clickedLink) {
clickedLink = e.target;
}
});
Or, you can apply any logic you want there. Sometimes, saving state like this in a semi-global for later use in a different event handler is a warning sign that you might have a design issue. If you explain more about what you're really trying to do, we could offer an opinion on whether there's a better way to solve your design issue.
Not sure if I fully understand the question. If you want to have two distinct bindings, you need two variables. Maybe so:
function parentFunction() {
var myVariable, anotherVariable;
someDiv.addEventListener('click', function (e) {
myVariable = e.target;
if (!anotherVariable) {
anotherVariable = e.target;
}
});
anotherDiv.addEventListener('click', function (e) {
// use anotherVariable
});
}

Categories

Resources