I've the following code. The return value of the function get_last_catergory_value is always undeifned. I've searched stackoverflow but couldn't debug the issue.
When I show the value being returned just before the return statement it shows the correct value. But when it is returned from function it is undefined. Can you please help me to resolve this?
function fetch_product(brand) {
var brand = brand;
//get last category id
var last_category = 'subcategory10';
var last_category_value = get_last_catergory_value(last_category);
alert(last_category_value); //undefined
}
function get_last_catergory_value(last_category) {
if($('.' + last_category).find(':selected').val() == 'none') {
last_category_number = last_category.substring(11);
last_category_number = parseInt(last_category_number);
last_category_number--;
last_category = last_category.substring(0, 11);
last_category = last_category + last_category_number;
get_last_catergory_value(last_category); //recall the function with values 'subcategory9', 'subcategory8' and so on...
} else {
var value = $('.' + last_category).find(':selected').val();
alert(value); //Gives the correct value here
return value;
}
}
Forgive me if its a trivial issue.
Thanks in Advance.
return statement is missing in the if block of get_last_catergory_value(last_category)
function get_last_catergory_value(last_category) {
if($('.' + last_category).find(':selected').val() == 'none') {
last_category_number = last_category.substring(11);
last_category_number = parseInt(last_category_number);
last_category_number--;
last_category = last_category.substring(0, 11);
last_category = last_category + last_category_number;
return get_last_catergory_value(last_category);
} else {
var value = $('.' + last_category).find(':selected').val();
alert(value); //Gives the correct value here
return value;
}
}
Related
Somehow when I set the preventDefault() within the function, it wouldn't work. I believe this is somehow a scope problem? if It is, how can I solve it though?
Can someone give me a hand?
Thanks in advance.
var abc = {
save: function () {
var $optionsRegex = this.$optionsRegex;
$('.save-options').on('click', function (e) {
e.stopPropagation();
var regex = '';
$.each($('.input-options'), function (index) {
var val = $(this).children('input').val();
if (val !== "") {
regex += (index + "," + val + ":");
}
});
return $optionsRegex.val(regex.slice(0, -1));
});
},
};
works fine if I didn't put it into an object though
this would work fine
$('.save-options').on('click', function (e) {
e.preventDefault();
var optionsRegex = '';
$.each($('.input-options'), function (index, value) {
var value = $(this).children('input').val();
if (!value == "") {
optionsRegex += (index + "," + value + ":");
}
});
return $('#id_options_regex').val(optionsRegex.slice(0, -1));
});
I have JavaScript calculator wherein I have defined two arrays as follows:
var degInc, degArr = [];
var radInc, radArr = [];
var PI = Math.PI;
var radStart = (-91*PI/2), radEnd = (91*PI/2);
for (degInc = -8190; degInc <= 8190; degInc+=180) {
degArr.push(degInc);
}
for (radInc = radStart; radInc <= radEnd; radInc+=PI) {
var radIncFixed = radInc.toFixed(8);
radArr.push(radIncFixed);
}
to be used in conjunction with the tangent function (below) so as to display a value of Undefined in an input (HTML below) should the user attempt to take the tangent of these values (I have included other relavent function as well):
Input -
<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/>
Functions -
function tan(form) {
form.display.value = trigPrecision(Math.tan(form.display.value));
}
function tanDeg(form) {
form.display.value = trigPrecision(Math.tan(radians(form)));
}
function radians(form) {
return form.display.value * Math.PI / 180;
}
with jQuery -
$("#button-tan").click(function(){
if (checkNum(this.form.display.value)) {
if($("#button-mode").val() === 'DEG'){
tan(this.form); // INSERT OTHER 'if' STATEMENT HERE FOR RAD ARRAY
}
else{
tanDeg(this.form); // INSERT OTHER 'if' STATEMENT HERE FOR DEG ARRAY
}
}
});
I would like to incorporate an array check within the .click function such that if the user input is contained in the array (degArr or radArr depending on the mode), the calculator returns Undefined. Now, I know how to display Undefined in the input display ($('#disp').val('Undefined')), but I cannot figure out how to configure an if statement that checks the relevant array. Is there a way to do so within the #button-tan function where I have commented?
Loop through the arrays on click and set a variable if you find a matched value.
You can do something like this:
$("#button-tan").click(function(e) {
e.preventDefault();
var userInput = $('#disp').val();
var buttonMode = $('#button-mode').val();
var displayVal = '';
if (buttonMode === 'DEG') {
var radFound = false;
radArr.forEach(function(item) { // changed from degArr
if (item === userInput) {
radFound = true;
}
if (radFound) {
displayVal = 'undefined';
} else {
tan(this.form);
}
});
} else {
var degFound = false;
degArr.forEach(function(item) {
if (item === userInput) {
degFound = true;
}
if (degFound) {
displayVal = 'undefined';
} else {
tanDeg(this.form);
}
});
}
});
You could create a simple object of a Calculator class, which keeps a reference to these arrays, and use like this. I changed some methods to receive the input as parameter rather than form.
$(function () {
function Calculator()
{
var degInc;
this.degArr = [];
var radInc;
this.radArr = [];
var PI = Math.PI;
var radStart = (-91*PI/2);
var radEnd = (91*PI/2);
for (degInc = -8190; degInc <= 8190; degInc+=180) {
this.degArr.push(degInc);
}
for (radInc = radStart; radInc <= radEnd; radInc+=PI) {
var radIncFixed = radInc.toFixed(8);
this.radArr.push(radIncFixed);
}
}
var calc = new Calculator();
function tan(input) {
alert("tan called");
var value = Math.tan(input.value);
alert("tan called. value: " + value);
input.value = value;
}
function tanDeg(input) {
alert("tanDeg called");
var value = Math.tan(radians(input));
alert("tanDeg called. value: " + value);
input.value = value;
}
function radians(input) {
alert("radians called");
var value = input.value * Math.PI / 180;
alert("radians called. value: " + value);
return value;
}
$("#button-tan").click(function(){
alert (calc.degArr);
alert (calc.radArr);
var displayInput = $("#disp");
alert("user input: " + displayInput.val());
if (!isNaN(displayInput.val()))
{
if($("#button-mode").val() === 'DEG')
{
if (calc.radArr.indexOf(displayInput.val()) > -1)
{
alert("user input is in radArr");
}
else
{
alert("user input IS NOT in radArr");
tan(displayInput);
}
}
else
{
if (calc.degArr.indexOf(displayInput.val()) > -1)
{
alert("user input is in degArr");
}
else {
alert("user input IS NOT in degArr");
tan(displayInput);
}
}
}
else
alert("Not a number in input");
});
});
If you wanna do some tests, I created a JSFiddle demo here. Type -8190 in the first input, then click the button. It's gonna be inside the array. Then try typing "DEG" in the second input and clicking again, you'll notice code will check against another array (due to IFs). I couldn't make your auxiliar functions to calculate a value, but I think this helps you with your initial problem.
indexOf should work...
$("#button-tan").click(function(){
if (checkNum(this.form.display.value)) {
if($("#button-mode").val() === 'DEG'){
if (radArr.indexOf(Number(this.form)) > -1) {
$('#disp').val('Undefined');
} else {
tan(this.form);
}
}
else{
if (degArr.indexOf(Number(this.form)) > -1) {
$('#disp').val('Undefined');
} else {
tanDeg(this.form);
}
}
}
});
I'm trying to repurpose a "legacy function" to pass a function with parameters into another function and get called. I've seen bits and pieces of what I'm looking for, but my arguments keep getting passed as a single string. This is the calling code - the 4th parameter (starts with '_delRideNew') is what I need to call.
MODAL.show("Confirm", "Are you sure you want to delete this ride?","Yes","_delRideNew('" + id + "','" + day + "','" + attuid + "')","No","MODAL.hide();")
Here is the MODAL.show code (using easyui):
MODAL.show = function(title, msg, okbtn, okcallback, canbtn, cancallback) {
if(arguments.length > 2) {
$.messager.defaults.ok = okbtn;
$.messager.defaults.cancel = canbtn;
}
else {
$.messager.defaults.ok = "OK";
$.messager.defaults.cancel = "Cancel";
}
if(arguments.length === 6) {
var me = $.messager.confirm(title, msg, function(r) {
if(r) {
//parse out function and args
var pos = okcallback.indexOf("(");
var func = okcallback.substring(0,pos);
var argss = okcallback.substring(pos,okcallback.length);
argss = argss.replace("(", "");
argss = argss.replace(")", "");
var argArray = argss.split(",");
window[func](argArray);
}
else {
cancallback;
}
});
me.window('move',{
left:400,
top:document.body.scrollTop+document.documentElement.scrollTop+200
});
}
else {
confirm(msg, function(r) {
if(r) {
return true;
}
else {
return false;
}
});
}
}
The problem is when the window[func] gets called it passes the array as a single string here:
function _delRideNew(id,day,attuid){
alert(id); //shows all 3 params as a string
var txtURL = 'delRide.cfm?tech_attuid=' + attuid + '&ride_date=#getParam("month")#/' + day + "/#getParam("year")#";
SYS.loadScript(txtURL);
status = txtURL;
}
It's very much possible that I'm doing this completely wrong, but any help would be, well..helpful.
This is my code:
var Evalcard = function(number) {
if (number == 1) {
this.name = "Ace";
this.value = 11;
}
else if (number == 11) {
this.name = "Jack";
this.value = 10;
}
else if (number == 12) {
this.name = "Queen";
this.value = 10;
}
else if (number == 13) {
this.name = "King";
this.value = 10;
}
return {this.name,this.value};
I'm pretty sure this return statement is not correct. How do you make a function return more than one value? Any help at all would be great.
In this case, you probably want to return either an array or an object literal:
return { name: this.name, value: this.value };
// later: EvalCard(...).name; EvalCard(...).number;
return [ this.name, this.value ];
// later: EvalCard(...)[0]; EvalCard(...)[1];
How about this:
return [this.name, this.value];
You could pass an object literal as you came so close to doing:
return { name:this.name, value:this.value };
or you could pass an array:
return [this.name, this.value];
Of course if your code is executed in the global context, you'll be setting name and value on the window object. If you're using Evalcard as a constructor, you wont need a return statement, the object being created will automatically be set:
var e = new Evalcard(1);
console.log(e.name); //outputs "Ace" if you remove the return statement.
Try:
return [this.name, this.value];
Try this...
function xyz() {
...
var x = 1;
var y = 'A';
return [x, y];
}
var a = xyz();
document.write('x=' + a[0] + ' and y = ' + a[1]);
Working example: http://jsfiddle.net/CxTWt/
var Evalcard = function(number) {
var evalName, evalValue;
if (number == 1) {
evalName= "Ace";
evalValue = 11;
}else if (number == 11) {
evalName = "Jack";
evalValue = 10;
}else if (number == 12) {
evalName= "Queen";
evalValue= 10;
}else if (number == 13) {
evalName= "King";
evalValue = 10;
}
return {name: evalName, value: evalValue};
}
alert(Evalcard(1).name+" "+Evalcard(1).value);
You need to change it to return an array or give keys to the object you are returning
So
return [this.name,this.value];
Or
return {name:this.name,value:this.value};
I would return an object:
return {key1:value1, key2:value2}
Then you can reference it like so:
myReturn.key1;
You can return it in a number of different ways:
Array
return [this.name,this.value];
Object
return {first:this.name, second:this.value};
String
return this.name+":"+this.value;
I am trying to pass a variable to a a function that I believe calls another function (I think) but am having problems. The variable I need to use in the second function is productid but several ways thAt I have tried have not worked. either a fix in javascript or Jquery will be great!!!
This is the line that I need the variable for
var error_url = '/ProductDetails.asp?ProductCode' + productid;
this is where the variable originates from...
var productid = form.elements['ProductCode'].value;
and here is the whole js code
function addToCart2(form, button) {
var softAdd = true;
var productid = form.elements['ProductCode'].value;
var qstr;
var bttnName = button.name;
button.disabled = true;
if (form.elements['ReturnTo']) {
form.elements['ReturnTo'].value = "";
}
qstr = serialize(form, bttnName + '.x', '5', bttnName + '.y', '5');
sendAjax('POST','/ProductDetails.asp?ProductCode=' + productid + '&AjaxError=Y', qstr , retrieveProductError2 ,displayServerError,false);
button.disabled = false;
return false;
}
function retrieveProductError2(result, statusCode) {
var ele = document.getElementById('listOfErrorsSpan');
var errorIndex = result.indexOf('<carterror>');
var productIndex = result.indexOf('<ProductIndex>')
if (errorIndex > -1 && productIndex == -1) {
var error_url = '/ProductDetails.asp?ProductCode' + productid;
window.location = error_url;
}
if (errorIndex != -1) {
//ele.innerHTML = result.slice(errorIndex + 11, result.indexOf('</carterror>'));
}
else {
ele.innerHTML = "";
if (productIndex == -1) {
sendAjax('GET','/AjaxCart.asp?GetIndex=True', '', showCart, null, false);
}
else {
productIndex = result.slice(productIndex + 14, result.indexOf('</ProductIndex>'));
sendAjax('GET','/AjaxCart.asp?Index=' + productIndex, '', showCart, null, false);
}
}
}
The easiest way is to just move your variable declaration outside of your method. So change the declaration of product id outside your addToCart2 method. So outside of that method you do this:
var product_id;
Then inside your method remove var from product_id and it will just be an assignment and not declaration.
Where you pass in retrieveProductError2 as your error callback for the sendAjax call, you could instead pass in:
function(result, statusCode) { retreiveProductError2(result, statusCode, productId);}
Then change the definition of your retreiveProductError2 function to accept the additional parameter.