jQuery javascript scoping problem - javascript

I have a hidden input element that I am using as a counter to use to name more input elements generated by JavaScript. To get the value of the counter i use
parseInt($('#counter').val());
However I use this code snippet several times in my code, so I thought it would be good to put it in a function
function getCounter(){
parseInt($('#counter').val());
}
this always returns undefined, while running just the code snippet returns the correct value. This happens in several ways that I tried defeining the function, as a function inside a $(function(){}), as a global function etc. How do I fix the scoping?

Add "return" to your return statement :)
function getCounter(){
return parseInt($('#counter').val());
}

How about adding a return
function getCounter(){
return parseInt($('#counter').val());
}

Related

jQuery val undefined

I'm trying to get the value of an input element on a html page using jQuery. I can get the element value using .val() if I call it from a script tag in the html page. However, when I call the same function from a seperate js file it returns undefined.
Anyone have anyidea what is going on here?
index.html
$(document).ready(function() {
console.log($("#amount").val()); // This works
externalFunction(); // This returns undefined
});
file.js
function externalFunction() {
console.log($("#amount").val());
}
EDIT
I should clarify that the div which contains the input element is hidden.
style="display: none;"
Would this make a difference?
When I call the same function from a seperate js file it returns
undefined.
If you mean the function returns undefined.
This is the correct behaviour because you returned nothing.
You have to use return statement.
function externalFunction() {
return $("#amount").val();
}
let value=externalFunction();
console.log(value);
if function is not found in your actual file.
Use export statement or require in order to make function visible in other file also.
As described in the question, that's simply not possible.
Instead, I suspect that you aren't calling externalFunction at the same time you're calling the console.log. Instead, I suspect you're calling it earlier, before the input exists.
There are only two reasons val ever returns undefined:
You call it on an empty jQuery object (because nothing matched the selector, for instance, because you called the function too soon).
You call it on a jQuery object whose first element is not an input or select (and thus has no value property).

"this" keyword is not working inside jquery function

I want to use "this" keyword within my jquery function but it doesn't works for me...
i have tried following ways:
1...
Not works....
function getRequest() {
var ReqPlace = $(this).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
}
2..
Not works....
var that=this; //also tried var that=$(this);
function getRequest() {
var ReqPlace = $(that).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
}
3..
Works but this time i have used a button
<input type="button" onclick="getRequest(this);" />
function getRequest(that) {
var ReqPlace = $(that).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
}
The above 3rd step is works pretty good but i don't need a button Is there any other way to use "this" keyword inside function
Thanks
this returns the instance of the object in which it was called.
In your case it does not work in statement 1 because for some reason you called this out of nowhere and returns you the instance of the function instead that is why it is not working
Same goes to statement 2 consider if the declaration
var that = this;
if this is inside a function this will return a function as well that is why it is not working.
And finally the reason statement 3 is working is it's returning the html object instance of the element since the function is a click event listener of an element. Take note that calling this in the function using statement 3 will work as well.
Well you can always use this in a function but remember that
$(query)
jQuery(query)
where query is an HTMLObject or an html string or a css selector string, sending it with a function will cause an error.
If you want to do something like this code inside a function
$(this).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
unless this is an HTML Object, what you should do is:
<div class='somedivinyourtemplate' id='hello'>
</div>
function () {
$('#hello').parent('div.reqHere')
.parent('div.allReqs').children('div.reqHere')
}
or just simply put an id of the element you want to select.
Hope that helps you understand how it works
if you want to use "this" in jquery
give id to button
<input type="button" id="getrequest" />
then
$("#getrequest").click(function(){
$(this).parent('div.reqHere').parent('div.allReqs').children('div.reqHere')
})

jQuery.each not running in function

I'm working on a project where some form elements depend on another form input to have a certain value, or possibly multiple elements with specific values before that input is shown.
The idea is that when the form is generated, the wrapping div for each input has a data-depends-on attribute with a comma-separated list of each field that it depends on to be shown, and the values for each that it's expecting to be shown.
I almost have the front-end / JavaScript code down to do the lifting, but for some reason my jQuery.each() loop in a JavaScript function isn't running even though I've confirmed the array I'm trying to loop through a. has content, and b. that the functioning is actually being called when it is expected to do so.
First, I have the actual function call (which is called whenever a dependency input is changed):
checkShowField(keyed_depends, current_vals, targeted_element);
And then the function checkShowField() definition:
function checkShowField(keyed_dependencies, current_values, targeted_element)
{
var hide_field = null;
jQuery.each(keyed_dependencies, function(key, value)
{
if (value != current_values[key] && hide_field == null)
hide_field = false;
});
if (hide_field == null)
$(targeted_element).slideDown();
else
$(targeted_element).slideUp();
}
Also please note that the function call is placed in the proper place, and is actually being called. I just added the code on here to show everyone context of how the function is being called. The function call is wrapped in $(document).ready(function() {...}.
So as you can see, in the function "checkShowField", I have a jQuery.each loop that should be looping through keyed_dependencies array, but in actuality, the loop isn't even running once. Thoughts?
You can check, if keyed_dependencies in argument list has a property length. If so, jQuery assumes an array and might actually fail to run you loop.
If that is the case, try using vanilla JS:
for (var key in keyed_dependencies) {...}
Hope that helps.
It looks like the keyed_dependencies is not really what you think it is. Try adding debugger; statements before the .each line and maybe in the function as well. Then use inspector/debugger to review the data in the variables.

Calling a Function stored in Variable from jQuery

I am trying to call a function typed variable from jQuery code. But don't know how to do that. eval() takes string input but I have function typed variable. I have tried the following code
if($.isFunction(successCallback)){
window[successCallback]();
}
Calling like a normal function worked.
successCallback()

Change eventListener function parameters based on iterator. (Vanilla JS)

What I want:
I have a method which takes an int as as its only parameter, then I'm creating a list where each element will call the other function when clicked, the only thing I want to change is the number that each element passes when clicked.
What I have:
while(++i<e){
(...)
a.addEventListener('click',function(){selectUser(i)},false);
(...)
}
Of course, the obvious problem is that when called, it will always pass the final value of 'i'.
I need that each element passes the value that 'i' had when it was created.
ie; when i=3, I want it to translate into:
a.addEventListener('click',function(){selectUser(3)},false);
I guess it involves some method which returns another method with the actual value, but I'm not really sure how to implement it. I have very little experience with js.
Thanks in advance.
This is a classic problem of closures. You must enclose your event handler inside a closure function which keeps the state of your variable i. Like this...
while(++i<e){
(...)
(function(index){
a.addEventListener('click',function(){selectUser(index)},false);
})(i);
(...)
}
This way every call of the wrapping function will keep your state of the variable i and thereby giving you the right result.
You have to create a new function scope. You could do it the following way (call an anonymous function, which in turn returns a new function with the specified i.
a.addEventListener('click',(function(index) {
return function(){ selectUser(index) };
})(i),false);

Categories