How to access variable value inside a function in javascript - javascript

I have searched on the website for solutions, but I have had no luck.
I need to make this data global. My code is present below:
function val() {
var plans = #json($plans);
var id = document.getElementById("plan_id").value;
plans.forEach(function(element) {
if (id == element.id) {
var i = element.amount;
return i;
}
});
}
var obj = val()
console.log(obj)
After I log that, it wont give any values but if I log inside the foreach, I will get the amount. Pls how can I access data inside foreach

Your function needs to return a value if you want to log it outside like this.
function val() {
const plans = #json($plans);
const id = document.getElementById("plan_id").value;
return plans
.filter(element => id === element.id)
.map(element => element.amount);
}
const obj = val()
console.log(obj)

You are not returning anything from the function and return inside forEach is always undefined. Use find
function val() {
var plans = #json($plans);
var id = document.getElementById("plan_id").value;
return plans.find(element => id === element.id).amount;
}
var obj = val()
console.log(obj)

This would on change get the amountValue from based on what ID you have selected.
var amountValue = null;
function val() {
var plans = #json($plans);
var id = document.getElementById("plan_id").value;
for (i = 0; i < plans.length; i++) {
if (id === plans[i].id) {
amountValue = plans[i].amount;
return amountValue;
}
}
}
var obj = val()
console.log(obj)

Thanks everyone, I have fixed my issue, but I follow another process.
I actually get the amount using onclick

Related

Using function of an object after grabbing it from array

When I try to grab the object from the array, the type is undefined. Therefore I cannot use a method from the undefined object as it doesn't exist. I am relatively new to JavaScript and I have come straight from Java so the way of retrieving objects is kind of new to me. This is what I currently have.
var fleetAmount = 0;
var fleets = [];
function Fleet(number) {
this.number = number;
this.activities = [];
this.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(this);
}
var getFleet = function(fleetNumber) {
return fleets[fleetAmount - fleetNumber];
}
This is where I try to grab the object and preform the function
const Fl = require(‘fleet.js’);
const fleet = Fl.getFleet(fleetNumber);
fleet.addActivity(activity);
I am also working in Node.js, which is how I am using the require method.
In combination with the answer from #audzzy I changed the getFleet() function so that it would be more efficient. I tested it out and it worked. This is what I used
function getFleet(fleetNumber) {
let result = fleets.filter(function (e) {
return e.number = fleetNumber;
})
return result[0];
}
Thanks for the help! I appreciate it.
you want to create a new fleet object and add it, not "this"..
adding "this" would cause a circular reference, where
this.fleets[i] = this (and all fleets would have the same value)
when calling get fleet, I would check that a fleet was returned from get fleet
in case amount is less than the number you send to getFleet (where according to what you posted: 1 returns the last, 2 returns second to last etc..)..
I hope this explanation makes sense.. anyways, this should work..
var fleets = [];
doStuff();
function doStuff(){
addFleet(1);
addFleet(2);
addFleet(7);
addFleet(3);
// should return null
let fleet1 = getFleetByNumber(5);
// should return the fleet with number 7, and not change the fleet with number 1
let fleet2 = getFleetByNumber(7);
if(fleet2){
fleet2.addActivity("activity");
}
console.log(`fleets: ${JSON.stringify(fleets)} \nfleet1: ${JSON.stringify(fleet1)} \nfleet2: ${JSON.stringify(fleet2)}`);
}
function addFleet(number) {
let fleet = { number: number,
activities: [] };
fleet.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(fleet);
}
function getFleetByNumber(fleetNumber) {
return fleets.find(function (e) {
return e.number == fleetNumber;
});
}
function getFleet(fleetNumber) {
let result = null;
if(fleets.length - fleetNumber >= 0){
result = fleets[fleets.length - fleetNumber];
}
return result;
}

javascript Assign the array inside variable

I am trying to assign a array inside a variable in javascript. But i am getting error like this. Could you please correct me where i have missed.
"TypeError: newItems.json is undefined"
var newItems = [];
if ($$('.selectvals:checked').length > 0) {
var i=0;
$$('.selectvals:checked').each(function (e) {
var row = e.parentNode.parentNode;
var jsonVals = row.down('.jsonval').value;
var jsonPaymentVals = row.down('amount').value;
newItems['json'][i] = jsonVals;
newItems['amount'][i] = jsonPaymentVals;
i++;
});
}
You need initialize right it, like this:
var newItems = {
json:[],
amount:[]
}

Cannot read property 'push' of undefined

I am trying to push data attribute value into array parameter but it throws the above error on the line parameter[parent].push(parent);
var parameter = {};
var currentTabSelected = "";
var parent = "";
$("#categories").on("click", ":checkbox", function () {
if($(this).is(":checked")) {
parent = $(this).data("parent");
console.log(parent)
if (!(currentTabSelected in parameter)) {
parameter[currentTabSelected] = []
}
var found = $.inArray($(this).val(), parameter[currentTabSelected]) > -1;
if (!found) {
parameter[currentTabSelected].push($(this).val());
parameter[parent].push(parent);
console.log(parameter)
}
} else {
var index = parameter[currentTabSelected].indexOf($(this).val());
var parent_index = parameter[parent].indexOf(parent)
if (index > -1) {
parameter[currentTabSelected].splice(index, 1);
parameter[parent].splice(parent_index , 1);
}
}
})
what can i do to overcome the above problem?
If parameter is an object you should create keys before using them.
You are trying to access the key which is not present in the parameter.
For example , make sure your object contains currentTabSelected and parent:
parameter[currentTabSelected] = []
parameter[parent] = []
After initializing currentTabSelected and parent you can perform operation on parameter[currentTabSelected], parameter[parent].
I suffered from the same issue few days ago, the solution is directly related with the 'this' keyword. Your 'this' is referring to another scope that your variable is not a part of. You might want to do a
var that=this;
Or if you're comfortable with ES6, you can use the arrow function syntax.

Cloning anonymous function

Hello I've used this patter to get a static variable
var uniqueID = (function() {
var id = 0; // This is the private persistent value
// The outer function returns a nested function that has access
// to the persistent value. It is this nested function we're storing
// in the variable uniqueID above.
return function() { return id++; }; // Return and increment
})(); // Invoke the outer function after defining it.
Now I'm trying to clone this function, but backup and the original still return sequential values. How can i "freeze" the status of the function when copy it?
Thanks
OK, something like this extremely convoluted contraption should work (fiddle, http://jsfiddle.net/dPLj6/):
var uniqueIdFunction = function(initialValue) {
var id = initialValue || 0;
var result = function() { return id++; };
result.clone = function(){ return uniqueIdFunction(id); }
return result;
};
var uniqueId1 = uniqueIdFunction();
Use the clone method to get a clone. The original will keep it's own internal id value. The clone will take its initial internal id from the clone source.
Here is a function that generates unique id generators:
var createGenerator = function(id) {
var id = id || 0;
return function() { return id++; };
}
var g1 = createGenerator();
var g2 = createGenerator();
console.log(g1(), g1(), g1());
console.log(g2(), g2());
console.log(g1());
console.log(g2());
// OP's cloning scenario
var freezeId = g1();
var clone = createGeenrator(freezeId);
console.log(g1(),g1());
console.log(clone());
#pax162's answer is more in line with what the OP wants to do. I just decided to post the more normal way of doing it.

looping through array of inputs to set value, "cannot set property value of undefined"?

I'm looking for a plain-Javascript way to fix my following code:
function autoFill(response) {
var arr = [];
arr.fn = document.getElementsByName("firstName")[1];
arr.ln = document.getElementsByName("lastName")[1];
arr.em = document.getElementsByName("Email")[1];
arr.pn = document.getElementsByName("phoneNumber")[1];
if(response === false) {
alert('false');
arr.forEach(function(entry){
entry.value = "";
});
}else{
alert('true');
arr.fn.value = response.firstName;
arr.ln.value = response.lastName;
arr.en.value = response.email;
arr.pn.value = response.phone;
}
}
What I'm trying to do:
if response data === false, loop through each element in arr[] and set its text value to empty "".
What's happening:
directly setting the values work (as shown in the else{} block), however looping or iterating through the array throws the error: Uncaught TypeError: Cannot set property 'value' of undefined
question:
how can I loop through a collection of inputs stored in an array and set their values? Why is the undefined error being thrown?
Thanks!
EDIT: changing to the following does nothing; the else{] block still works fine, the loop is the problem I believe.
function autoFill(response) {
var arr = [];
arr["fn"] = document.getElementsByName("firstName")[1];
arr["ln"] = document.getElementsByName("lastName")[1];
arr["em"] = document.getElementsByName("Email")[1];
arr["pn"] = document.getElementsByName("phoneNumber")[1];
if(response === false) {
alert('false');
arr.forEach(function(entry){
entry.value = "";
});
}else{
alert('true');
arr["fn"].value = response.firstName;
arr["ln"].value = response.lastName;
arr["en"].value = response.email;
arr["pn"].value = response.phone;
}
}
You need to use an object not an array and you should use "dot notation" for better clarity.
EDIT
I changed the code because I dont like to say "no you can't" so here's the new function with loop.
function autoFill(response) {
var fill = {};
for (var i=0; i < document.myForm.elements.length; i++) {
var elm = document.myForm.elements[i]; // Get current element.
fill[elm.name] = elm; // Associate fill[input name] with current input.
if (elm.getAttribute("data-autofill") === "undefined" ||
elm.getAttribute("data-autofill") === null) continue; // Continue if property data-autofill is not set.
// If response have the input name as key, we set the value otherwise, it would be an empty string or unchecked.
switch(elm.type) {
case 'checkbox':
case 'radio':
response.hasOwnProperty(elm.name) ? fill[elm.name].checked = response[elm.name] : fill[elm.name].checked = false; // Checked if response if true.
break;
default:
response.hasOwnProperty(elm.name) ? fill[elm.name].value = response[elm.name] : fill[elm.name].value = ""; // Set response text or a empty string.
}
}
return fill; // Return object for later uses.
}
var myForm = autoFill({
firstName: "John",
check: true,
ni: "Not supposed to be set" // Won't set because he doesn't have the property data-autofill.
});
myForm.lastName.value = "Awesome"; // Now we can set values like this because we returned all form elements.
And the jsFiddle.
To reuse the names in each area of the function, add them to an array and iterate over them BUT you need to ensure that the properties in response and your DOM element names match.
function autoFill(response) {
var arr = ['firstName', 'lastName', 'Email', 'phoneNumber'];
var obj = {};
arr.forEach(function (el) {
obj[el] = document.getElementsByName(el)[1];
});
if (response === false) {
alert('false');
for (var k in obj) {
obj[k]['value'] = "";
}
} else {
alert('true');
arr.forEach(function (el) {
obj[el]['value'] = response[el];
});
}
}
You should store input fields into an array as
arr[0], arr[1] and access them with index.
you have declared: var arr = []; then assigned arr.fn, arr.ln n so..
Either declare var arr = {}; or assign arr.fn, arr.ln as arr[0], arr[1].
When you assign,
var arr = [];
arr["fn"] = document.getElementsByName("firstName")[1];
and observe the value of arr, it will be empty. so declare it as var arr= {}.

Categories

Resources