Unable to return value from a function - javascript

I want to return value from the function which contains an anonymous function.
function getSingleCheckedItemId() {
return $(".data-table-chk-item").each(function() {
if ($(this).is(":checked")) {
var value = $(this).attr("value");
return value;
}
});
}
In this case it returns me the array of all checkboxes. If I remove the first return, it won't return a value but undefined.
So how do I return the value from getSingleCheckedItemId()?

.each always returns the jQuery object containing all elements that you iterated over so:
function getSingleCheckedItemId() {
var ret;
$(".data-table-chk-item").each(function() {
if ($(this).is(":checked")) {
ret = $(this).attr("value");
return false; //breaks out of .each
}
});
return ret;
}
Also, this.value is usually a better option than $(this).attr('value') in case you're dealing with form inputs - seems like you have radio/checkbox inputs due to their checked property. Also, this.checked returns a boolean so there's no need for $(this).is(':checked') either.
I believe your logic can be simplified to:
function getSingleCheckedItemId() {
return $(".data-table-chk-item:checked").val();
}
This way .val() will return the value of the first :checked item or undefined if no elements are matched by the selector, which does the same as the loop above.

You can do it:
function getSingelCheckedItemId() {
var elements = $(".data-table-chk-item:checked");
return (elements.length > 0) ? $(elements[0]).val() : undefined;
}

I would do it like this
function getSingleCheckedItemId() {
var ret;
$(".data-table-chk-item").each(function() {
if ($(this).is(":checked")) {
ret = $(this).attr("value");
}
});
return ret;
}

Related

jquery return true or false according custom function

I want to bind following code in custom function and return true if field has value and false if field is empty. Validating with only one variable, it was easy. But when validating two array I think it can be possible only custom function. I think code becomes unnecessarily lengthy as well because of lack of custom function. Please guide me.
$(document).on('click', '.subadd', function(){
//I want to bind this code in function
var sid = [];
$('input[name="sid[]"]').each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
};
if($(this).val()){
$(this).removeClass('border1red');
sid.push(this.value);
}
});
var title = [];
$('input[name="title[]"]').each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
};
if($(this).val()){
$(this).removeClass('border1red');
title.push(this.value);
}
});
//function
//if function return true
if(sid.length && title.length){
$('table#menutable tr:last').after("<tr>.....</tr>");
};
});
First you can shorten your each loop.
if(!$(this).val()){
$(this).addClass('border1red');
return false;
} else {
$(this).removeClass('border1red');
title.push(this.value);
}
You can also make a function for that, with the selector and the array as parameters.
$.validate = function(selector, array) {
$(selector).each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
} else {
$(this).removeClass('border1red');
array.push(this.value);
}
}
}
In the end, the main section of the code would look like this:
var sid = [];
var title = [];
$.validate('input[name="sid[]"]', sid);
$.validate('input[name="title[]"]', title);
if(sid.length && title.length){
$('table#menutable tr:last').after("<tr>.....</tr>");
};

_.each find value in array return true or false. using underscore js

//find value in array using function checkValue using underscoreJS _.each.
//return true, else false.
var helloArr = ['bonjour', 'hello', 'hola'];
var checkValue = function(arg) {
_.each(helloArr, function(helloArr, index) {
if (arg[index] === index) {
return true;
}
return false;
});
};
alert(checkValue("hola"));
The problem with your code is that, _.each will iterate through all the elements of the array and call the function you pass to it. You will not be able to come to a conclusion with that, since you are not getting any value returned from it (unless you maintain state outside _.each).
Note that the values returned from the function you pass to _.each will not be used anywhere and they will not affect the course of the program in any way.
But, instead, you can use _.some as an alternate, like this
var checkValue = function(arg) {
return _.some(helloArr, function(currentString) {
return arg === currentString;
});
};
But, a better solution would be, _.contains function for this purpose. You can use it like this
var checkValue = function(arg) {
return _.contains(helloArr, arg);
};
But, since you have only Strings in the Array, the best solution would be to use Array.prototype.indexOf, like this
var checkValue = function(arg) {
return helloArr.indexOf(arg) !== -1;
};
Try this:
var helloArr = ['bonjour', 'hello', 'hola'];
var checkValue = function(arr, val) {
_(arr).each(function(value) {
if (value == val)
{return console.log(true);}
else {return console.log(false);}
});
};
console.log(checkValue(helloArr,'hello'));
/* Output
false
true
false*/

ngShow/ngHide using a function

I have a button that I want to hide when the array $scope.game.players.players contains specific value.
button(ng-click="", ng-hide="ImPlaying()") Play
The function ImPlaying() checks the condition and return a boolean
$scope.ImPlaying = function(){
$scope.game.players.playerExist($scope.user.socketID, function(exist){
console.log(exist);
return exist;
});
}
exist change value but the button is always shown
But when I replace the function $scope.game.players.playerExist() by its code everything works as expected.
$scope.ImPlaying = function(){
for (var i = 0; i < $scope.game.players.players.length; i++) {
if($scope.game.players.players[i]){
if($scope.game.players.players[i].socketID == $scope.user.socketID){
return true;
}
}
};
return false;
}
What's wrong with the first function ?
You're missing return statement in ImPlaying function
$scope.ImPlaying = function(){
return $scope.game.players.playerExist($scope.user.socketID, function(exist){
console.log(exist);
return exist;
});
}

Adding the results of a function to an array

I have numerous input boxes that I'm trying to store the names of into an array. I'm using this currently to get the names:
var getImplementedNames = function (selector){
$(selector).each(function() {
console.log($( this ).attr('name').replace('imp-', ''));
});
}
console.log(getImplementedNames('[id^=imp]'));
This works, but now I'd like to add all the reslts to an array. I've tried;
var array = [getImplementedNames('[id^=imp]')];
console.log(array);
Which returns an undefined array.
I'm not sure of how this is supposed to be properly handled.
Use .map()
var getImplementedNames = function (selector) {
return $(selector).map(function () {
return $(this).attr('name').replace('imp-', '');
}).get();
}
usage
console.log(getImplementedNames('[id^=imp]'));
Read Return Value from function in JavaScript
Your function isn't currently returning anything. Try:
var getImplementedNames = function (selector){
return $(selector).map(function() {
return $( this ).attr('name').replace('imp-', '');
});
}
console.log(getImplementedNames('[id^=imp]'));

Pass anonymous function to jquery selector expr[:]

In jQuery, you can run a selector where every element is run through a function you define, like this (totally contrived example):
jQuery.expr[':'].AllOrNothing= function(a,i,m){
// a is the thing to match, m[3] is the input
if(m[3] === "true"){
return true;
} else {
return false;
}
};
Then you can use it like:
$("div:AllOrNothing(" + true + ")"); //returns all divs
$("div:AllOrNothing(" + false + ")"); //returns nothing
Is it possible to pass an anonymous function instead of calling jQuery.expr[:].Name= ?
Edit
I'm envisioning something chainable like the following:
$("div").filterByFunction(function(a,i,m){ ... })
It sounds like you just want to use the built-in .filter() method and pass it a custom function that examines sibling elements to decide whether to return true or false and then hide the remaining elements.
$("section").filter(function() {
// examine child div and return true or false
}).hide();
For completeness, you could an implementation of filter yourself with by adding to $.fn
$.fn.customFilter = function(f) {
var filtered = $();
this.each(function() {
if(f.call(this)) {
filtered = filtered.add(this)
}
});
return filtered;
}
$("div").filterByFunction(function(){ return $(this).text() != "test"; })
Not that you should, in this case.

Categories