My java script array doesn't have a length - javascript

I have the following code:
//Populate inputData with the values of the input text boxes, in order
var inputData = {};
var x = document.getElementById("newInventoryForm");
//Added this following line in the edit
$('#additionalContent').append("My x.length property " + x.length + "<br/>");
for (var i = 0; i < x.length - 1; i++) {// -1 so we don't get the submit button
var addData = {
id : x[i].id,
value : x[i].value
};
inputData[i] = addData;
$('#additionalContent').append(inputData[i].id + " : " + inputData[i].value + "<br/>");
}
I'm attempting to pass the form data from a previously made form to another javascript function. Before I do that I have tried to make it all work in the same .js page, however when I try to output my inputData through a for loop, it shows up blank. I determined this is because inputData.length is undefined. I was under the impression that declaring it as inputData = {}; made it an array and thus had a default length value. How can I change this to have the correct length?
Edit
Several commenters have said that var x = document.getElementById("newInventoryForm"); should return null or a node, neither of which has a length property. Adding the line in the code above, has produced this output.
My x.length property 18
serialNumber : 456
someDatafield : someInput

You've declared it as an object.
Perhaps var inputData = []; will give you better results.

{} is an object, not an array.
You want [].
Also, getElementById() does not return an array; your entire code makes no sense.

Related

Can I assign an array value to a variable?

I can't seem to assign an array value to a variable. It always returns undefined.
In my code I have set currentWord = text[wordPos]. At the end of the code I have console logged currentWord, and text[wordPos]. My thinking says that they should return the same value, but they don't. currentWord returns undefined, and text[wordPos] returns the correct value (the first word in the 'text' array).
Solved. I had mistakenly forgot that I had 2 arrays, and thought the text array was not empty, but it was. The words array is the array I had filled in separate file.
var text = Array();
var wordPos = 0;
var currentWord = text[wordPos];
function gen() {
text = [];
var random;
for (var i = 0; i < 10; i++) {
random = words[Math.floor(Math.random() * 50)];
text.push(random);
}
document.getElementById('text').innerHTML = text.join(" ");
console.log(currentWord);
console.log(text[wordPos]);
}
Currentwork is undefined because you create an array object but never push a value into it. It transfers the current value of the variable not the reference.
There is no value at index 0 of text. If you assign some values to the text array you should be good!
Updated:
Read the OP's note above about the two arrays in the original example. In light of this information, the following script simulates an imported array words of 50 distinct values in order to generate a text of ten space-delimited numbers and indicate its first value:
// simulating an array imported from a separate file
var words = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50];
function gen() {
var wordPos = 0;
var currentWord = "";
var arr = [];
var randomVal;
var d = document;
d.g = d.getElementById;
var pText = d.g('text');
// get each of 10 values by randomly selecting an element's key
for (var i = 0; i < 10; i++) {
randomVal = words[ Math.floor( Math.random() * 50 ) ];
arr.push( randomVal );
}
pText.innerHTML = arr.join(" ");
currentWord = arr[wordPos];
console.log("Current word: ",currentWord );
}
gen();
<p id="text"></p>
This script randomly selects 10 numbers and adds them to an empty array by means of variable randomVal. This variable acquires a value in each iteration of the for-loop, during which the variable is passed to the push() method of arr in order to append it to the array. Once the loop terminates, the script joins the elements of arr on a blank space character, which yields a string whose numeric values are space-delimited.
One can discern that the script is working correctly when the console.log statement displays the first numeric value appearing in the text.

JavaScript Array.shift not working

I have been programming a system that is supposed to delete the first index of an array. Instead of changing an array from (i.e) "1,2,3,4,5" to "2,3,4,5" the console gives an error: "Uncaught TypeError: num.splice is not a function". I have heard that num.splice is not a function, it is an operation (or something) to delete the first indexed value of the array. I am confused that when I use an example code from w3Schools, there is no outputted error in the console. I don't understand why this happens.
(I have given the entire code just in case it has to do with syntax issues)
function dCrypt() {
var num = document.getElementById("demoin").value; // ex: a127
var key = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var mod = 0;
var out = 0;
var prep = 0;
var pre = 0;
num.split("");
mod = num[0];
pre = key.indexOf(mod);
num.splice(0,1);
for (i=0;i <= pre;i++) {
prep += 26;
}
out = Math.floor(num + pre);
document.getElementById("demoout").innerHTML = out;
}
Thanks in advance!
When you split 'num' you have to reassign it
num = num.split("");
Referring to your link from w3schools:
The splice() method adds/removes items to/from an array, and returns the removed item(s).
As you can see the var num is string(and not an array) and has the value of the element with id demoin.
Since you are trying to splice a string and not an array. The error shows up in the console.
Solution:
Either store the value of your split in an array(it could be num itself) and then splice that array.
num = num.split("");
...
num.splice(0,1);

Google Sites Listitem

I am working with the google sites list item.
The classes are Here and Here
I have been able to iterate through the columns and put all of the column headers in to one array with the following code.
//Global
var page = getPageByUrl(enter URL here)
var name = page.getName();
function getInfo() {
var columns = page.getColumns();
//Get Column Names
for (var j in columns) {
var cName =columns[j].getName();
columnList.push(cName);
}
}
Now I want to be able to get each row of the listitem and put it in its own array.
I can add the variable
function getInfo() {
var columns = page.getColumns();
var listItems = page.getListItems();//new variable
//Get Column Names
for (var j in columns) {
var cName =columns[j].getName();
columnList.push(cName);
}
}
Now that I have the variable the output is [ListItem, ListItem, ListItem, ListItem]
So I can use a .length and get a return of 4.
So now I know I have 4 rows of data so based on my wants I need 4 arrays.
Small interjection here, Not a coder by trade but code as a precursor to wants becoming needs.
A buddy of mine who is a JS coder by trade showed me this code which does work. With the logger added by me.
for (var i in listItems) {
if (listItems.hasOwnProperty(i)) {
item = listItems[i];
for (var x = 0; x < columnList.length; x++) {
attrib = item.getValueByName(columnList[x]);
Logger.log("Logging value of get list page get value by name = " + columnList[x] + " " + attrib);
}
}
}
Which brings the total code to
var name = page.getName();
var listItems = page.getListItems();
var listCount = listItems.length
var listList = [];
var columns = page.getColumns();
var name = columns[0].getName();
var item, attrib = 0;
var columnList = [];
Logger.log(listItems);
Logger.log(name + " was last updated " + page.getLastUpdated());
Logger.log(name + " was last edited " + page.getLastEdited());
var listCount = 0;
//Get Column Names
for (var j in columns) {
var cName =columns[j].getName();
columnList.push(cName);
}
Logger.log(columnList);
// Get index of Due Date
var dueDateValue = columnList.indexOf("Due Date");
Logger.log("The index of due date is " + dueDateValue);
for (var i in listItems) {
if (listItems.hasOwnProperty(i)) {
item = listItems[i];
for (var x = 0; x < columnList.length; x++) {
attrib = item.getValueByName(columnList[x]);
Logger.log("Logging value of get list page get value by name = " + columnList[x] + " " + attrib);
}
}
}
}`
Forgive the above code as it has been a bit of a sketch pad trying to work this out.
I am a bit behind on understanding what is happening here
for (var i in items) { // This is for each item in the items array
if (items.hasOwnProperty(i)) {
if items is an array, how can we use has own property? Doesn't that belong to an object? Does an array become an object?
My questions are two category fold.
Category # 1
What is happening with the hasOwnProperty?
-Does the array become an object and thus can be passed to .hasOwnProperty value
Category # 2
Is this the only way to take the values from the listitem and populate an array
- If it is, is there some way to delimit so I can pass each row into it's own array
- If it isn't , why does it work with the hasOwnProperty and why doesn't it work without it in the example below
for (var i in listItems) {
for (var y = 0; y < columnList.length; y++) {
item = listItems[i];
listList = item.getValueByName(columnList[x]);
Logger.log("Logging my version of list naming " + listList);
}
In which I get a "Invalid argument: name (line 41" response. Highlighting the
listList = item.getValueByName(columnList[x]);
Not looking for a handout but I am looking to understand the hasOwnPropertyValue further.
My current understanding is that hasOwnValue has to do with prototyping ( vague understanding ) which doesn't seem to be the case in this instance
and it has to depend on a object which I described by confusion earlier.
To clarify my want:
I would like to have each row of listitems in its own array so I can compare an index value and sort by date as my current column headers are
["Project", "Start Date" , "End Date"]
Any and all help is much appreciated for this JS beginner of 2 weeks.
An array can be inside of an object as the value of a member:
{"myFirstArray":"[one,two,blue]"}
The above object has one member, a name/value pair, where the value of the member is an array.
Here is a link to a website that explains JSON.
Link To JSON.org
JSON explained by Mozilla
There are websites that will test the validity of an object:
Link to JSONLint.com
An array has elements, and elements in an array can be other arrays. So, there can be arrays inside of arrays.
.hasOwnProperty returns either true or false.
Documentation hasOwnProperty
Interestingly, I can use the hasOwnProperty method in Apps Script on an array, without an error being produced:
function testHasProp() {
var anArrayTest = [];
anArrayTest = ['one', 'two', 'blue'];
Logger.log(anArrayTest);
var whatIsTheResult = anArrayTest.hasOwnProperty('one');
Logger.log(whatIsTheResult);
Logger.log(anArrayTest);
}
The result will always be false. Using the hasOwnProperty method on an array doesn't change the array to an object, and it's an incorrect way of using Javascript which is returning false.
You could put your list values an object instead of an array. An advantage to an object is being able to reference a value by it's property name regardless of where the property is indexed. With an array, you need to know what the index number is to retrieve a specific element.
Here is a post that deals with adding properties to an object in JavaScript:
StackOverflow Link
You can either use dot notation:
objName.newProperty = 'newvalue';
or brackets
objName["newProperty"] = 'newvalue';
To add a new name/value pair (property) to an object.

Using for loops

alert(cellvalue) shows three seperate pop ups:
-10-|Car|*POB*[,]-20-|Bus|*CLR*
-22-|Car|*CLR*[,]-5-|Bus|*POB*
-12-|Car|*POB*[,]-55-|Bus|*CLR*
I am then splitting these values and getting the three values I need as follows:-
var array = cellvalue.split("[,]");
var start_carStat = array[0].indexOf('*') + 1;
var end_carStat = array[0].indexOf('*',start_carStat);
var text_carStat = array[0].substring(start_carStat,end_carStat);
alert(text_carNum); shows '10', '22', '12'
var start_carNum2 = array[1].indexOf('-') + 1;
var end_carNum2 = array[1].indexOf('-',start_carNum2);
var text_carNum2 = array[1].substring(start_carNum2,end_carNum2);
alert(text_carNum); shows '20', '5', '55'
and then returning them as follows:-
return (text_carNum+', '+text_carNum2);
Since there could be upto 20 values in each array I am trying to use a for loop to achieve the same thing but I can't seem to get it to work.
At the moment I have:-
for(var i=0;i<array.length;i++){
var start_carNum = array[i].indexOf('-') + 1;
var end_carNum = array[i].indexOf('-',start_carNum);
var text_carNum = array[i].substring(start_carNum,end_carNum);
return (text_carNum);
}
with this alert(text_carNum) only shows '10','22','12'.
Any ideas on how I could get this to work the same way as above using for/each?
(hoping I have explained this clear enough)
You call return in your loop, so the function exits at the end of the first iteration. You have to concatenate all values in a variable :
var str_return = '';
for(var i=0;i<array.length;i++){
var start_carNum = array[i].indexOf('-') + 1;
var end_carNum = array[i].indexOf('-',start_carNum);
var text_carNum = array[i].substring(start_carNum,end_carNum);
str_return += '<span style="color:'+color+' !important;">'+text_carNum +'</span>';
}
return str_return;
BTW, notice that I change the last line : the style attribute was closed (double quote) just after the color, it has to be closed after !important.
return will always exit the function as soon as it is called. In your code, it is only able to reach array[0] before it leaves the loop.
A solution would be to append the values of array to another variable within your loop, and then return a value after the loop has finished.

Javascript - Compare value to Associative array index

I have the following code:
var license_price = 0;
var num_licenses = jQuery('#num_licenses').val();
var lp = {};
lp[1]=12.50;
lp[10]=15.50;
lp[50]=50.00;
for(var index in lp) {alert(index);
if (num_licenses >= index){
license_price = parseFloat(lp[index]);
}
}
//alert(license_price);
jQuery('#total_price').val((num_licenses * license_price));
This code determines the value entered in the num_licenses box, then goes through the array lp and assigns a price based on the value of each key. So, if num_licenses = 8, the price should be 12.50 each, if the num_licess = 60, the price should be $60.
It works for all values except 2 - 9. If I enter 2-9, the price from fp[10] is used. But, if it is 1, then I get 12.50.
take care,
lee
When you iterate over the object's indices they are typed as strings. Your > comparison is actually sorting them alphabetically rather than numerically. Parse its numeric value to get this working. (alphabetically '2' occurs after all values starting with '1', including '10', so '2' > '10', etc.)
for(var index in lp) {
alert(index);
if(lp.hasOwnProperty(index)) { // prevent comparison when property inherited
if (num_licenses >= parseInt(index,10) ){
license_price = parseFloat(lp[index]);
}
}
}
The problem is that you are comparing a string to an integer. The result of the val() function is a string. Therefore, if your input is '2' , the result of '2' <= 10 is false. You should convert it first to an integer using the parseInt() function.
Here's what it should look like:
var license_price = 0;
var num_licenses = parseInt(jQuery('#num_licenses').val(),10);
var lp = {};
lp[1]=12.50;
lp[10]=15.50;
lp[50]=50.00;
for(var index in lp) {alert(index);
if (num_licenses >= index){
alert("Greater than " + index);//added this for debugging
license_price = parseFloat(lp[index]);
}
}
//alert(license_price);
jQuery('#total_price').val((num_licenses * license_price));
Note that I added a parseInt() call to the value. I also added some alert calls so you can see what is happening.
Here is a link to a jsFiddle snippet so that you can test it out: http://jsfiddle.net/CmbvW/8/
In your code lp is a Object not a array, so index is a property name with type String.
Try to change your code to
var lp = [];
then the index will be a number.

Categories

Resources