Javascript: Passing variable from function to function - javascript

I'm new to Javascript and I have a problem passing a variable from function to function:
$(document).ready(function () {
$('input[type=checkbox]:checked').removeAttr('checked');
var filename = document.getElementById("Tagg").value;
var checkboxesH = $('input[type="checkbox"][name="tags[]"]');
checkboxesH.change(function () {
$('input[type="text"][name="tags"]').val(filename);
var current = checkboxesH.filter(':checked').length;
});
});
in the checkboxesH.change function, filename is always null! why? When the page opens, there is a string in the textfield tags.
Thank you.

Javascript passes the value of the variable at the time of the function creation. To fix this problem you should simply call
document.getElementById("Tagg")).value
in your .change() function directly. This way, it will reflect the state at change time, not when the change event handler was created.

Related

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;

Passing argument to function I don't want to execute immediately

Sorry if my question seems naive (a bit of a newbie here), but I seem not to be able to get a simple answer to my question.
In JavaScript I try something like this
window.onload = init; *// ok, this assigns to the window load event a function that doesn't execute straight away*
// now I define my init()function
function init(){
// say...
alert('Noise!');
/* but here is my dillema...
Next say I want to assign to an button.onclick event a function that only executes when I click the button.
But (!here it is...!) I want to pass arguments to this function from here without causing to execute because it (obviously) has brackets.
Something like: */
var button = document.getElementById('button');
var promptInput = prompt("Name?");
button.onclick = printName(promtInput); // I only want to print name on button click
}
function printName(name){
alert(name);
}
So... OK, I know the example is stupid. Simply moving all prompt gathering inside printName() function and assign to button.onclick a bracketless printName function will solve the problem. I know. But, still. Is there a way to pass args to functions you don't want to execute immediately? Or it really is a rule (or 'by definition') you only use functions that await execution when you don't plan to pass args via it?
Or how do you best to this thing otherwise?
Thanks a lot!
Ty
button.onclick = function() {
printName(promptInput);
};
You can use Function.prototype.bind():
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
For example:
button.onclick = printName.bind(null, promtInput);
You could put the data that you would normally pass as an argument into some other holding location. You can either put it in a hidden HTML element, or you can use the sessionStorage API to keep it. So your code would look like this:
var button = document.getElementById('button');
var promptInput = prompt("Name?");
sessionStorage.setItem('MyName', promptInput);
button.onclick = printName; // I only want to print name on button click
}
function printName(){
alert(sessionStorage.getItem('MyName');
}

onclick function runs automatically

Using google apps script I'm having trouble running a js function which passes parameters. When I add the parameters it will always run the code when the page loads instead of when the button is clicked.
Direct from the HtmlService example, it is OK - it runs when the button is pressed...
document.getElementById('button1').onclick = doSomething;
But when I add a parameter to the call (and function) as below, it runs just once when the page loads (and not when the button is pressed)...
document.getElementById('button1').onclick = doSomething('with_this_parameter');
Any insight into this behaviour would be greatly appreciated... sorry if the answer is obvious!
When you say
document.getElementById('button1').onclick = doSomething('with_this_parameter');
This means call doSomething('with_this_parameter') and then assign the returned value to document.getElementById('button1').onclick. Hence that is why it gets called when code reaches that line. Whether the value is assignable to that property or not is another question, but that is why it gets called.
Use it like this
document.getElementById('button1').onclick = function(){
doSomething('with_this_parameter');
}
Reference: This solution was given by Mark Linus.
Do like this:
document.getElementById('button1').onclick = function(){
doSomething('with_this_parameter');
}
To assign a reference of function to some variable, you do:
var a = doSomething;
where doSomething is a function.
But when you have to pass parameters and assign that function
var a = doSomething(b);
this will cause trouble as while assigning the function to the variable, it gets called and not when it is intended to be called.
To overcome this, you can use arrow functions or simple function to call your own function with params.
var c = () => doSomething(d);
This actually is understood as var c = anonymous_function;
or
var c = function() {
doSomething(d);
}
Hence you can do:
document.getElementById('button1').onclick = () => doSomething('with_this_parameter');
I usually do clickHandlers like so:
// create button here or get button...
var button1 = document.getElementById('button1').setName('button1');
var clickHandler = app.createServerClickHandler('doSomething');
button.addClickHandler(clickHandler);
function doSomething(e){
var button1 = e.parameter.button1;
<do something with var button>
}
I'm not sure what parameter you are adding, but you need to add a callback element to pass it if it isn't passed by the button itself via a .setId/getId or .setTag/getTag. If it is from a textbox:
var textbox = app.createTextBox();
var button1 =
app.createButton.setName('button1');
var clickHandler =
app.createServerClickHandler('doSomething').addCallbackElement(textBox);
button1.addClickHandler(clickHandler);
Hope this helps!

get returned result after click event in JQUERY

I have a function that return value and i executed the function after click event for example
$("some_div").click( my_function());
The answer is how to get the returned value of the function.
i couldn't use
var something = $("some_div").click( my_function());
Thanks to every one who contribute the the question.I've got my answer.
You have to pass a function to click, not its return value. In the event handler you can call your function and deal with the return value as you see fit:
$("some_div").click(function() {
var result = my_function();
// do whatever you want with `result`
});
The event handler is not called immediately, but some time later (when the element is clicked). Therefore it does not make sense for .click to return a value.
You could declare a global Variable and write the result into that. Here is an example that writes the current event into global:
var global = ''
$("#some_div").click(function(e){
global = e;
});
You can't get a return value, You only subsrcibe a callback function that will be fire when clicking "some_div".
If you want to use some value from callback function, use it inside the function or save it in a hidden input
$("some_div").click(function() {
var someValue = foo();
$('#hiddenInputName').val(someValue);
});
//later on...
var extractedValue = $('#hiddenInputName').val();

Categories

Resources