Use JavaScript value from jquery to javaScript function - javascript

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 );
}

Related

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.

Not able to define function

I am writing something like
(function($){
function showAlert(){
alert('test');
}
})(jQuery);
and when I tried to run showAlert(), it's saying showAlert() is not defined.
Can anyone suggest why ?
The scope of a variable in javascript is either
the global scope
the function in which it is defined
showAlert is a variable. It's only available in the scope of the external function you wrote.
If you want to define a function for the external scope, define it in the external scope.
I suppose you're calling that function outside IEFE function.
Calling it outside won't work as it is not in global scope. The IEFE is creating a closure of which , showAlert becomes a part and not of global scope which is window
Do this:
(function($){
window.showAlert = function(){
alert('test');
}
})(jQuery);
It doesn't make sense to put a function declaration inside IEFE unless otherwise it is a jquery plugin. So, just remove it:
function showAlert(){
alert('test');
}
You're Creating A function inside a self executing anonymus function ie. $(document).ready() or $(function()....
So your function is in local scope of that function. Simply Means You cant access that in outside of that function.
So to make it accessible just make it global.
In JavaScript window is global object. So to make your function global, use that object as follows:
$(document).ready(function() {
function showAlert()() {
alert('test');
}
window.showAlert=showAlert(); //NOTE THIS, IT IS IMPORTANT.
});
Now you can access it elsewhere in your JS.
Here is working Fiddle
Hope it'll help you! cheers :)..
If you want to extend jQuery with your function just add function to jQuery object.
Like this:
(function ($) {
$.extend({
showAlert: function () {
alert('test');
}
});
}(jQuery));
Separate this code into file with name jquery.showAlert.js, include it after jquery library
and after this you can use function in this way:
$.showAlert()
Best regards.
This should work!
function showAlert(x) {
alert(x);
}
showAlert($('#anyElementId').val());
Assign the variable X for function and your alert. Then pass your element val into your function call.
Demo: http://jsfiddle.net/94ZtT/

function inside while loop

What Im trying to do is to get the content of a specific textarea tag in a specific clicks of a button, so I think a loop will solve this problem. The while loop on PHP does the role of making the name of textarea different and button's onclick trigger. But the loop in javascript wont work. Please anyone help what is the right one to complete my task?? Sorry for bad english...Thanks in advance
<html>
<head>
<script>
var i = 0;
while(i < 2000)
{
i++;
function feedbacks+i()
{
var feed = document.getElementsByName("feedback"+i)[0].value;
alert(feed);
}
}
</script>
</head>
<body>
<?php
while($i < 2000)
$i++;
echo "<textarea name='feedback$i' >you post</textarea>";
echo "<button onclick='feedbacks$i()' >send feedback</button>";
?>
</body>
</html>
I'm not sure if i get your question right, but why don't you write one single javascript function and pass the index as a parameter?
like:
function feedbacks(index) {
var feed = document.getElementsByName("feedback"+index)[0].value;
alert(feed);
}
and
onclick='feedbacks($i)'
Your code is incorrect, Since you have tagged your question with Jquery, I would like to suggest the following solution,
$(document).ready(function(){
$(document).on('click','button',function(){
alert($(this).prev('textarea').val())
});
});
You are creating those elements textarea and the button in runtime, So you have to use delegation inorder to register the click event for those buttons. Additionally you have to wrap your code inside .ready() function, Which means you have to manipulate the DOM only after it got ready.
Please see here for references,
.on (for delegation)
.ready()
.prev()
You have two major problems here.
Naming your function
When you name a function, you can't use variables, only a single identifier.
You could use a function expression and then assign the result somewhat that you can identify with a variable. e.g.
an_array_i_created_earlier[i] = function () {
// etc etc
}
Closures
You are trying to use i inside the function you are creating, but you are changing it outside that function before that function runs.
You can get around this by creating a new closure.
function createFunction(i) {
return function () {
// can use i sanely here because it was passed into a local variable belonging to `createFunction`
};
}
an_array_i_created_earlier[i] = createFunction(i);
This is all very messy though. You can forget about having to deal with i entirely, and throw out the horribly intrinsic event attributes while you are at it. Instead, navigate through the DOM to find the element:
addEventListener('click', function (evt) {
var textarea, t = evt.target;
if (t.classList.contains('feedback')) {
textarea = t.previousElementSibling;
alert(textarea.value);
}
});
Note that this uses some fairly recent additions to browser DOM. If you want compatibility with older browsers (in particular IE9 and earlier) then you will probably want to rewrite it to add some support for legacy approaches. A library like YUI or jQuery can help with that.
There's some error in your JavaScript code:
You tried to define a sequence of functions in a loop, and the function became local function to that loop. You cannot get access to these functions outside the loop. In order to make this work, you should define the function on window object, with the syntax window["feedbacks1"] = function () {}.
function feedbacks+i() is invalid syntax, use window['feedbacks' + i], as pointed in (1).
Functions defined in loop will share some local variable (closure). The variable in the function feedbacks#{i} will all share the same i. After the loop, i became 2001 and all the functions defined will try to get textarea with name feedbacks2001, which of course will not work. You will need the (function (i) { /* the code using i */ })(i); trick to make a local copy of the shared variable.
I made a demo on jsFiddle which correct the mistakes. I showed only 2 textareas. The following javascript should work for you 2000 textareas case.
for (var i = 0; i <= 2; ++i) {
window["feedbacks" + i] = (function (i) {
return function (e) {
var feed = document.getElementsByName("feedback"+i)[0].value;
alert(feed);
};
})(i);
}

Reuse function without global variables?

A couple of days ago I have learned on my own example how bad global variables and functions are. So apparently the best solution is NOT to use them, however sooner or later I will need to reuse my variables and functions over and over again.
So my question is: Can I reuse my functions and variables without declaring them globally? Can it be done?
For example, I want to reuse my alertBox function and my containsP variable couple of times:
DEMO: http://jsfiddle.net/ajmyZ/
//I am BAD GLOBAL FUNCTION inside var
//But I am reusable!!!
var alertBox = function () {
alert("Hey I am BAD function!!")
}
$(document).ready(function () {
//I am BAD GLOBAL var
//But I am reusable TOO!!!
var containsP = $("div p:first");
containsP.click(function () {
alert("Hi BAD var HERE!!");
});
$("p").eq(1).click(function () {
alertBox();
});
//I am the NICEST function here
//but I am NOT reusable :(
$("p").eq(2).click(function () {
alert("I am the NICEST function here!!");
});
});
I guess the simplest way to avoid clobbering the global object is just to create your own "application context". You can do that, by creating a self-invoking function which wraps your whole js-code within each file.
(function( win ) {
"use strict";
var still_global_but_only_in_this_anonymous_closure = true;
$(document).ready(function() {
// ...
// accessing the global object:
win.some_global_property = true;
});
}( this ));
Actually, you're already creating such a local context with your anonymous function you pass into .ready(). This is just the more explicit way. That self-invoking method, just calls itself with the global object as argument (where you still can explicitly access global variables). Furthermore, by invoking "use strict"; you're protected from accidently creating global variables alá "Ops_I_Forgot_The_Var_Statment = true;
The code you posted has no global variables. A variable declared inside of a function (in the case of your example, the anonymous document.ready handler) will never be global unless you make one of two mistakes:
forget the var keyword, making an implicit global
explicitly say window.myVar = ...;

how to get a variable over to a function?

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.

Categories

Resources