How to access a predefined array in AngularJS - javascript

I'm facing an issue with accessing the array element in AngularJS. I have an array:
$scope.salesentry = [
{
sales_id:'',
product_id: '',
product_category_id:'',
sale_qty:null,
sale_amount:null
}
];
I want to update the sales_id field value on some button click like:
$scope.saveData = function() {
$scope.salesentry.sales_id='10';
});
I'm not able to access it in the above way. How can I do so?

salesentry is an array, so you need to access a specific element on it first using [0].
So your code becomes:
$scope.saveData = function() {
$scope.salesentry[0].sales_id='10';
});

Do you want to update each salesentry's sales_id ?
If yes you may use
angular.foreach($scope.salesentry, function(value, key){
value.sales_id = 10;
});

You need to index the array
$scope.salesentry[0].sales_id = '10'
Also, no need for the comma at the end.

Related

Find a variable in a array variable

I am trying to get load a variable from a array variable for my project but the value comes back as undefined I just used the console.log for the test output.
I want to learn how to use it after seeing others use on their projects and I want to do it to make my projects easier to manage.
I set it to trigger when the page loads up first thing.
Any help is welcome from the community.
My code if it helps solve it problem:
window.addEventListener('load',function(){
var values = [
odds_base = 10,
start_cash = 50
]
console.log(values.odds_base)
});
In this case I think you have to use an object like this one, instead of array:
window.addEventListener('load',function() {
var values = {
odds_base: 10,
start_cash: 50
};
console.log(values.odds_base);
});
You are using the wrong data structure here. Square brackets are used for arrays. You should use a javascript object here.
window.addEventListener('load',function(){
var values = {
odds_base: 10,
start_cash: 50
}
console.log(values.odds_base)
});
Or you can do like this
let values = {};
values.odds_base = 10;
values.start_cash = 50;
console.log(values.odds_base);
If that is array then you have to use variables like this
window.addEventListener('load',function(){
var values = [
odds_base = 10,
start_cash = 50
]
console.log(values);
console.log(odds_base);
console.log(start_cash);
});
When you assign array like this then Internally JavaScript first Creates the variable and then assign those variables in array
Otherwise convert that array to object and do like as follows
window.addEventListener('load',function(){
var values = {
odds_base : 10,
start_cash : 50
}
console.log(values);
console.log(values.odds_base);
console.log(values.start_cash);
});
The value of values looks like it should be an object and not an array as seen in your example i.e. values = [ a = 1, b = 2 ] should be values = { a: 1, b: 2 }
window.addEventListener('load', function(){
var values = {
odds_base: 10,
start_cash: 50
}
console.log(values.odds_base)
});
Tip: Declare the values variable outside the scope of the addEventListener callback if you wish it to be accessible outside also.

Using jQuery to gather data from HTML attributes

I'm trying to put together a web form to mark an indeterminate number of employees as either present or absent. The page itself contains an arbitrary number of divs of the form:
<div class="employee" empID="9" presence="0">
The divs themselves contain the options, with 'presence' being changed to 1 or 2 using jQuery depending on the option selected.
When the 'submit' button is pressed, I'd like to convert this data into a parsable array of pairs of 'empID' and 'presence'. I've tried doing this with jQuery as follows:
$('.cic-button').click(function(){
var submitData = {employees:[]};
$('firedrill-employee').each(function(){
submitData.push({
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
});
However, when this is done, the submitData variable is failing to populate. Any idea why? Am I going about this in the correct manner? Is what I'm trying to do even possible?
Many thanks.
You have a few errors. Make the class that you iterate over the collection of "employee" not "firedrill-employee" and don't forget the dot to indicate it's a class. Reference the employees array withing the submitData object. You can't just push an element into an object.
$('.cic-button').click(function () {
var submitData = {
employees: []
};
$('.employee').each(function () {
submitData.employees.push({
employeeID: $(this).data('empID'),
presence: $(this).data('presence')
});
});
console.log(submitData);
});
Fiddle
Js fiddle
$('.cic-button').click(function () {
var submitData = [];
$('.employee').each(function () {
var self = $(this);
// Create and obj
var obj = new Object(); // {};
obj["employeeID"] = self.attr("empID");
obj["presence"] = self.attr("presence");
//push that object into an array
submitData.push(obj);
console.log(obj);
console.log(submitData);
});
});
You need to specify the employee array as such:
$('.cic-button').click(function(){
var submitData = {employees:[]}; // employees is an array within submitData...
$('.firedrill-employee').each(function(){
submitData.employees.push({ // ...so amend code here to push to the array, not submitData
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
console.log(submitData);
});
See example JSFiddle - http://jsfiddle.net/yng1qb6o/

How to convert a bunch of arrays into a single object?

Here is what im doing:
onClick, grab details immediate subnodes and publish it on html. Status = DONE // This works well
NOW, I am using a bunch of arrays to get this done.
node.eachSubnode(function(node) {
title[title.length] = node.name; // This is what i want to modify
data[data.length] = node.data; // This is what i want to modify
});
Here is how they look currently:
title = ['Coffee', 'Tea'];
data = ["Americans", "Britishers"]; // i use a loop to iterate through these arrays and append to html.
Here is what i want it to be:
var preference = {
title: 'Coffee',
data: 'Americans'
},
{
title: 'Tea',
data: 'Americans
}
I want to create this using the node.eachSubnode loop.
I'm not sure if I understood correctly, but I think this is what you want:
var preferences = [];
node.eachSubnode(function(node) {
preferences.push({
title: node.name,
data: node.data.germ
});
});
You cannot create an object that looks exactly like that, I think you need an array with objects. Assuming your node is an array with the length property, this method is the fastest.
var preference = new Array(node.length||0), i = 0;
node.eachSubnode(function(node) {
preference[i++] = {
title: node.name,
data: node.data.germ
};
});

How to create array dynamically with javascript

Im trying something which is probably very easy but i cant seem to find out why its not working. Im trying to dynamically create and array with jquery/javascript.
my code;
var icons = $('.icon');
var desktopicons = [];
var user = { name: username };
var iconsetup = { myicons: [] };
desktopicons.push(user);
desktopicons.push(iconsetup);
$.each(icons, function() {
var name = $(this).attr('name');
var rel = $(this).attr('rel');
var icon = {
icon: [{
name: name,
rel: rel
}]
};
iconsetup.myicons[0].push(icon);
});
desktopicons.push(user);
desktopicons.push(iconsetup);
$('#desktop').append(desktopicons[0].name);
$('#desktop').append(desktopicons[1].myicons[0].icon[0].name);
Somehow my log file says cannot call method push of undefined on 'iconsetup.myicons[0].push(icon);' this line.
Anyone who can tell me how to create the array? Thanks!
You are using myicons[0] which means you get the first item of the myicons and that is not an array
Use
iconsetup.myicons.push(icon);
You could also simplify the whole .each() section with
iconsetup.myicons = icons.map(function(idx, item){
return {icon:[{name: item.name, rel: item.rel}]}
}).get();
You are trying to push the icon to myicons[0] which is undefined, instead you need to push to myicons which will add the icons to your array:
iconsetup.myicons.push(icon);
You never set iconsetup.myicons[0] equal to anything. iconsetup.myicons is simply an empty array with nothing in it, and no element 0. Maybe you meant:
iconsetup.myicons.push(icon);

Creating a key/pair object using jQuery and some inputs

I have a cart on my website and I need to let users easily change the quantity of items they have in their cart at a moment.
Here is the javascript code I have so far:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var items = [];
$(".item").each(function () {
var productKey = $(this).find("input[type='hidden']").val();
var productQuantity = $(this).find("input[type='text']").val();
items.addKey(productKey, productQuantity); ?
});
// 1. Grab the values of each ammount input and it's productId.
// 2. Send this dictionary of key pairs to a JSON action method.
// 3. If results are OK, reload this page.
});
</script>
The comments I wrote are just guidelines for me on how to proceed.
Is there a way to add a key/pair element to an array of sorts? I just need it to have a key and value. Nothing fancy.
I wrote in an addKey() method just for illustrative purposes to show what I want to accomplish.
items[productKey] = productQuantity;
In JavaScript, Arrays are Objects (typeof(new Array)==='object'), and Objects can have properties which can be get/set using dot- or bracket- syntax:
var a = [1,2,3];
JSON.stringify(a); // => "[1,2,3]"
a.foo = 'Foo';
a.foo; // => 'Foo'
a['foo']; // => 'Foo'
JSON.stringify(a); // => "[1,2,3]"
So in your case, you can simply the productQuantity value to the productKey attribute of the item array as such:
items[productKey] = productQuantity;
items[productKey]; // => productQuantity
You can add anonymous objects to the items array like:
items.push({
key: productKey,
quantity: productQuantity
});
Then access them later as items[0].key or items[0].quantity.
Also you can use JQuery.data method and like that you can also get rid of those hidden.

Categories