Assign variable set in one function to a variable in another function - javascript

I'm trying to assign the variable strSel in the function outputSelected to the variable TestVar in the function testResults. What's the best way to achieve this?
function getSelected(opt) {
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if ((opt[intLoop].selected) || (opt[intLoop].checked)) {
index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}
function outputSelected(opt) {
var sel = getSelected(opt);
var strSel = "";
for (var item in sel)
strSel += sel[item].value + ",";
window.document.title = strSel;
}
function testResults (form) {
var TestVar = // Want to pass strSel here.
window.document.title=(TestVar);
}

Just use a global variable :-
then set this variable in one function and you can use this variable value in another function.
var myvar;// declare global variable
function outputSelected(opt) {
var sel = getSelected(opt);
var strSel = "";
for (var item in sel)
strSel += sel[item].value + ",";
// set the var:-
myvar=strSel ;
window.document.title=(strSel); <----- result
}
function testResults (form) {
var TestVar= myvar;
//alert (TestVar + "\n" + TestVar1 + "\n" + TestVar2 + "\n" + TestVar3 + "\n" + TestVar4 + "\n" + TestVar5);
window.document.title=(TestVar);
}

You can use a global variable or return the value in the function outputSelected() and call and assign it in your other function.

You could return the value from outputSelected and then pass it into your testResults method:
Changes:
function outputSelected(opt) {
// current code
return strSel;
}
function testResults(form) {
var TestVar = form;
window.document.title = TestVar;
}
And call the methods like so:
testResults(outputSelected(opt));

Related

how to return this value from my function? is it wrong method?

I don't understand how to solve the following problem when return the value from nested function. is it wrong method. How can I get it?
My basic purpose is to get array values (all coordinates) from var mymap_coordinates, but it can't. that's why I use .toString() to test.
*<script>
mymap.on( //leftlet code
'contextmenu',
function (event)
{
var tg_marker = L.marker(event.latlng, {icon: treegroupIcon}).addTo(mymap);
store_coordinates[incre_coord] = new Point(tg_marker.getLatLng().lat.toFixed(8), tg_marker.getLatLng().lng.toFixed(8));
var n = store_coordinates.length;
var mymap_coordinates = abcdefg(store_coordinates, n);
window.alert (mymap_coordinates.toString()); //This alert can't print all array value when return the value from abcdefg function
incre_coord = incre_coord + 1;
}
);
function abcdefg(points, n)
{
.......
.......
.......
// return Result
var num = 0;
var map_coordinate = new Array();
for (let temp of abc.values())
{
map_coordinate[num] = "[" + temp.x + ", " + temp.y + "]";
num = num + 1;
}
window.alert (map_coordinate.toString()); //This alert can print all array value
return map_coordinate;
}
</script>*

JSON return value to global variable

Simply my code looks like this:
var thevariable = 0;
For(){
//somecode using thevariable
$.getJSON('',{},function(e){
//success and i want to set the returned value from php to my variable to use it in the forloop
thevariable = e.result;
});
}
my main problem that the variable value stays "0", during the whole For loop, while i only want it to be "0" at the first loop, then it takes the result returned from PHP to use it on for loop.
here it my real code if you need to take a look:
var orderinvoice = 0;
for(var i=0; i<table.rows.length; i++){
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g,'')).replace(/Qty /g,'');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g,'');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', {'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink}, function(e) {
console.log();
document.getElementById("result").innerText= document.getElementById("result").innerText + "Order #"+e.result+" Created Successfully ";
document.getElementById("invoker").innerText = ""+e.invoice;
orderinvoice = e.invoice;
if(i+1 == table.rows.length){
document.getElementById("result").innerText= document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
});
in a loop block, before one ajax complete other one will be run and this's javascript natural treatment. For your case you can call a function at the end of success event. Do something like this:
var i = 0;
doSt();
function doSt() {
var orderinvoice = 0;
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g, '')).replace(/Qty /g, '');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g, '');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', { 'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink }, function(e) {
console.log();
document.getElementById("result").innerText = document.getElementById("result").innerText + "Order #" + e.result + " Created Successfully ";
document.getElementById("invoker").innerText = "" + e.invoice;
orderinvoice = e.invoice;
if (i + 1 == table.rows.length) {
document.getElementById("result").innerText = document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
i++;
if (i < table.rows.length) doSt();
});
}
I think you need a recursive function that always deals with the first element in your rows array and then splices it off and calls itself. For example, something like this:
function getStuff(rows, results) {
if (rows.length > 0) {
var ordername = rows[0].cells[5].innerText;
$.getJSON('orderprocess.php', { 'ord_name': ordername }, function (e) {
// do some stuff
results.push('aggregate some things here?');
rows.splice(0, 1);
return getStuff(rows, results);
});
} else {
return results;
}
}
When the array is spent, results will be returned with whatever aggregate you wanted at the end of the cycle. Then, you can do as you please with the results. I think you can also manipulate the DOM inside the function as you see fit if that makes more sense. Hope this helps.

add an object or edit if exist (indexeddb)

I have this code and i can add or edit the object if exists, but the "for" finish before the function onsuccess is called, then the index "for" is bad.
How to pass the index onSuccess?
Help!!!
var active = dataBase.result;
var data = "";
var object = "";
var index = null;
var request;
$(".layers").promise().done(function () {
var elements = document.getElementsByClassName('layers');
for (var i = 0; typeof (elements[i]) != 'undefined'; i++) {
if (elements[i].getAttribute("src").split("/")[4] !== "alpha.png") {
data = active.transaction([elements[i].getAttribute("src").split("/")[3]], "readwrite");
object = data.objectStore(elements[i].getAttribute("src").split("/")[3]);
index = object.index("by_Name");
request = index.get(String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]));
request.onsuccess = function (e) {
var result = e.target.result;
if (result === undefined) {
var resultPut = object.put({
Name: String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]),
Count: 1,
Type: String(elements[i].getAttribute("src").split("/")[4])
});
resultPut.onerror = function (e) {
alert(resultPut.error.name + '\n\n' + resultPut.error.message);
};
} else {
result.Count++;
var requestUpdate = object.put(result);
requestUpdate.onerror = function (event) {
alert(requestUpdate.error.name + '\n\n' + requestUpdate.error.message);
};
}
}(event);
}
}
alert("Finish");
})
The thing is that, by the time the for has ended, the transactions with the object store are not. What you could try is to encapsulate the index like this:
for(var i = 0; i < elements.length; i++) {
(function(myElement) {
if (myElement.getAttribute("src").split("/")[4] !== "alpha.png") {
...
}
})(elements[i]);
}

Using for-in loop inside object to access its member

function Cons()
{
this.a = "variable a";
this.callme = function callme()
{
var str = "";
for(var x in this)
{
str += this[x] + " ";
}
return str;
}
}
var obj = new Cons();
obj.c = "variable 2";
var fin = obj.callme();
document.write(fin);
I want to have a function inside the object so that when it is called it can return a string consisting of the values of every member. Here in this case a and c. Now what happens, everything inside the function i mean the code is printed inside the browser instead of just returning the value of str.
What i understood is that this["callme"] part in the for-in loop returns the whole code as its also a variable. So how to solve this problem.
I am new to javascript please help me.
There are several ways to solve this:
1) Remove callme from the for..in :
for(var x in this) {
if (x !== 'callme') {
str += this[x] + " ";
}
}
2) Declare callme as a non-enumerable property:
function Cons() {
Object.defineProperty('callme', {
enumerable : false,
value : function callme() {
var str = "";
for(var x in this)
{
str += this[x] + " ";
}
return str;
}
});
}
3) Change the toString method of callme to return nothing:
function Cons() {
this.a = "variable a";
this.callme = function callme() {
var str = "";
for(var x in this)
{
str += this[x] + " ";
}
return str;
}
this.callme.toString = function(){ return '';};
}
The simplest solution is the first one, but the others are too interesting to pass.
If you want to avoid the function body being printed, check if the property is a function and print only its name:
this.callme = function callme()
{
var str = "";
for(var x in this)
{
if ('function' === typeof this[x]) {
str += x + " ";
} else {
str += this[x] + " ";
}
}
return str;
}

JavaScript, How can I parse a variable into a command?

What I'm trying to do is to enable multiple checkboxes within for(). Right now it looks like this, but from what I have learned, you can't run the command from a variable like this, I can't run, (e.g) cab_type_value = "whatever". Nor can I run road_load_enabled; it just doesn't work. Does anyone how I can achieve this? How can I parse my var J in the document.MyForm.InputName.disabled?
for( var j=1; j<=14; j++ ) {
var cab_type_value = "document.exe_mode_form.cab_type" + j + ".value";
var cab_type_checked = "document.exe_mode_form.cab_type" + j + ".checked == 1";
for( var i=1; i<=document.exe_mode_form.road_load_number.value; i++ ) {
var road_load_value = "document.exe_mode_form.load" + i + ".value";
var road_load_enabled = "document.exe_mode_form.load" + i + ".disabled = false";
var road_load_disabled = "document.exe_mode_form.load" + i + ".disabled = true";
var rld_db = "document.exe_mode_form.a" + i + "_a1.value";
if ( cab_type_checked ) {
if ( test == 1 ) {
if(road_load_disabled) {
alert("road_load_disabled");
road_load_enabled;
}
test = 2;
}
if(cab_type_value == rld_db) {
if(olof == 1) {
alert("cab_type_value == rld_db");
olof = 2;
}
road_load_enabled;
}
}
}
}
Also, this part isn't working:
if(cab_type_value == rld_db) {
if(olof == 1){
alert("cab_type_value == rld_db");
olof = 2;
}
road_load_enabled;
}
And I have checked, cab_type_value has the same value as rld_db.
try changing these kind of lines:
var cab_type_value = "document.exe_mode_form.cab_type" + j + ".value";
to:
var cab_type_value = document.exe_mode_form['cab_type' + j].value;
The same logic holds for function calls:
someVariable = 'alert';
window[someVariable]('Foo!');//alerts foo
If your function is not declared in the global scope, you can replace window with any namespace object: foobarObject.orEven.nestedOnes[someVariable]();And finally, because I personally loathe the window keyword (it's a circular reference), you can simply choose to use this['alert']('foo'); in a regular function call or in the global scope. this points to its called context, which in these cases is the global object

Categories

Resources