Jquery function return value - javascript

I've created a function to iterate through a UL/LI. This works perfectly, my problem is returning the value to another variable. Is this even possible? What's the best method for this? Thanks!
function getMachine(color, qty) {
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
return thisArray[3];
}
});
}
var retval = getMachine(color, qty);

I'm not entirely sure of the general purpose of the function, but you could always do this:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:
function getMachine(color, qty) {
var returnValue = null;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
returnValue = thisArray[3];
return false; // this breaks out of the each
}
});
return returnValue;
}
var retval = getMachine(color, qty);

Related

toString method on Linked List implementation not working in js

I'm working through Cracking the Coding Interview and I thought I'd implement all the data structures in JS 5. Can anyone explain to me why my toString method isn't working?
Thanks!
function Node(data) {
this.next = null;
this.data = data;
}
Node.prototype.appendToTail = function(data) {
var end = new Node(data);
var n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}
Node.prototype.toString = function(head) {
console.log(head)
if (head == null) {
return ""
} else {
return head.data.toString() + "-> " + head.next.toString();
}
}
var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);
console.log(ll.toString())
function Node(data) {
this.next = null;
this.data = data;
}
Node.prototype.appendToTail = function(data) {
var end = new Node(data);
var n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
};
Node.prototype.toString = function() {
var returnValue = String(this.data);
if (this.next) {
returnValue = returnValue + "-> " + String(this.next);
}
return returnValue;
};
var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);
console.log(String(ll))
or avoid this kind of problems completly and do not use prototype, class, this, call, etc
Your toString function takes an argument, but you're not passing it when you call toString.
If you want to access the node, you should use this, instead of passing in a value
Node.prototype.toString = function() {
var result = this.data.toString();
if (this.next) {
result += "-> " + this.next.toString();
}
return result;
}

how to print the return value of a function in jquery

I want to print the return value from a function
$(document).ready(function () {
$('.click').click(function (e) {
var value = 1;
check(value); //function call with value:value=1
alert(val); //here i want to return the value from function
});
function check(value) {
if (value == 1) {
var val = 'success';
return val;
} else {
var val = 'error';
}
}
}); //document ready function
so how to acieve the return value of the function and print the value of the function which was returned
You would do this:
var value = 1;
var valofvalue = check(value); //function call with value:value=1
alert(valofvalue); //here i want to return the value from function
Or, even shorter:
var value = 1;
alert(check(value));
The reason it wasn't working is because val is not a global variable - it was made only in the check() function and no one other than the things inside check() can access it. So I made another variable, valofvalue, to store the return value and use it in the click function.
Even better, to save making multiple variables, put the val variable all the way at the top of the function, so you don't need to return anything:
$(document).ready(function () {
var val = '';
$('.click').click(function (e) {
var value = 1;
check(value);
alert(val);
});
function check(value) {
if (value == 1) {
val = 'success';
} else {
val = 'error';
}
}
});

how to return right value in js?

I am trying an angular program but cant return the right value:
function facilityChecked(facility, search) {
var result;
search.filter(
function (v) {
var rtn = (v["facility_Item"]["text"] == facility);
if (rtn) {
var checked = (v.inherit_To_Service === 'true');
result = checked;
}
else {
result = false;
}
}
);
return result;
}
In the code below $scope.parking should be true and $scope.toilet should be false however they both return as false?
parking = facilityChecked('Parking', rtn.Organisation.Facility);
$scope.parking = parking;
toilet = facilityChecked('Toilet', rtn.Organisation.Facility);
$scope.toilet = toilet;
See also this plunkr link
This function is using filter which loops through each item in the array, so it is always setting result to the value of the last item in the array...
so init result to start, and if the value is found, then parse it out of the item
function facilityChecked(facility, search) {
var result = false;
search.filter(
function (v) {
var rtn = (v["facility_Item"]["text"] == facility);
if (rtn) {
var checked = (v.inherit_To_Service === 'true');
result = checked;
}
}
);
return result;
}
Here the problem is with else part in search.filter(); Actually, search.filter() function is executing for all the Json objects.So, it stores and returns the last object value i.e false".
I think, else part is not necessary, because you taking the values from data.json.
function facilityChecked(facility, search) {
var result;
search.filter(
function(v) {
var rtn = (v["facility_Item"]["text"] == facility);
if (rtn) {
var checked = (v.inherit_To_Service === 'true');
result = checked;
}
}
);
return result;
}
Updated Plunker:http://plnkr.co/edit/SETl5Zqapsdp8FmB6t56?p=preview

Javascript function can write to console but not returning value

I have a function in javascript which can write the output to the console but it is unable to return the value..
fetchData: function(dateToFetch){
if (mP.viewMode == 1){
$.each(mealData.DailymPs, function(k, item){
if( item.Date == formatDate(mP.chosenDate) ){
mP.DayPlan.mPDayData = item;
return mP.populateMealDayPlan();
}
})
} else if (mP.viewMode == 2){
// debugger;
$.each(mealData.DailymPs, function(k, item){
if( item.Date == (dateToFetch) ){
mP.DayPlan.mPDayData = item;
console.log(mP.populateMealDayPlan());
var returnObj = mP.populateMealDayPlan();
return returnObj;
}
})
}
}
You should be able to fix it by changing it from:
...
$.each(mealData.DailymPs, function(k, item){
if( item.Date == (dateToFetch) ){
mP.DayPlan.mPDayData = item;
console.log(mP.populateMealDayPlan());
var returnObj = mP.populateMealDayPlan();
return returnObj;
}
})
...
to
...
var returnObj = null;
$.each(mealData.DailymPs, function(k, item){
if( item.Date == (dateToFetch) ){
mP.DayPlan.mPDayData = item;
console.log(mP.populateMealDayPlan());
returnObj = mP.populateMealDayPlan();
return false; // break out of each()
}
})
if(returnObj != null) return returnObj;
...
Note: You'll also need to externalize the return variable in the if condition. I've demonstrated how that can be done for the else condition.
If you want to return something from a $.each loop, assign it to a variable in the outer scope, return false; to break the loop and then return it after the $.each(); call.
Without seeing mP.populateMealDayPlan, my first guess would be that calling the function twice to get the values changes some internal values of mP. In other words if I am right and you comment out the console.log, there should be a return value. You could also do:
var returnObj = mP.populateMealDayPlan();
console.log(returnObj);
rather than calling mP.populateMealDayPlan in the console.log
If this is not the case then I think we would need more context in order to help.
Your return statement returns from the function passed to the each method, not from your fetchData function. The grep function will be useful here:
fetchData: function(dateToFetch) {
var selector = mP.viewMode == 1 ? function(item) { return item.Date == formatDate(mP.chosenDate) } : function (item) { return item.Date == dateToFetch};
var matched = $.grep(mealData.DailymPs, selector);
if (matched.length) {
var item = matched[0];
mP.DayPlan.mPDayData = item;
console.log(mP.populateMealDayPlan());
return mP.populateMealDayPlan();
}
}

Retrieve value of element on dom on page reload

I have the following JavaScript function which is used to keep users from inundating our server with Ajax requests:
var validateZip = function () {
var lastSuccessful = parseInt(jQuery('#mailingZip').val(), 10);
return {
validate: function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
}
}();
This page is reloaded if users input a bad zip code or other errors appear on the form. However since the dom hasn't loaded yet, I always pull NaN from that field.
Placing it in the on document ready for jQuery means that I can't call the function directly.
How can I modify my scope such that the lastSuccessful will remain "private" and get the value once the dom is ready?
function validateZip() { // use function declaration, not function expression
var lastSuccessful = parseInt(jQuery('#mailingZip').val(), 10);
return {
validate: function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
}
}; // removed premature invocation of function
jQuery(validateZip); // call it on document ready instead
Why can't you call it in ready event? Of course you can enclose it into another function:
$(functon(){
var validateZip = function () {
var lastSuccessful = parseInt(jQuery('#mailingZip').val(), 10);
return {
validate: function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
}
}();
});
The question is you you need to keep validateZip function as defined global? If you only run it at this point, just omit its declaration and just write:
$(functon(){
(function () {
var lastSuccessful = parseInt(jQuery('#mailingZip').val(), 10);
return {
validate: function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
}
})();
});
Don't know why I didn't think / do this before. I created a getter/setter on my return function, then on the document ready just called the setter with that value.
var validateZip = function() {
// Track the last sent in zip code -- treat this as private data
var lastSuccessful = "";
return {
validate : function(zip) {
var is5DigitNumber = /^\d{5}$/;
if (is5DigitNumber.test(zip) && lastSuccessful !== zip) {
lastSuccessful = zip;
return true;
} else {
return false;
}
},
setLastSuccessful : function(zip) {
lastSuccessful = zip;
},
getLastSuccessful : function() {
return lastSuccessful;
}
}
}();
jQuery(document).ready( function() {
validateZip.setLastSuccessful(jQuery('#mailingZip').val());
});

Categories