var formRules = $(this).data('rules');
var formValues = $(this).data('values');
if(formRules || formValues){
var rulesArray = formRules.split(',');
var valuesArray = formValues.split(',');
for(var i=0; i < rulesArray.length; i++){
//alert(rulesArray[i]);
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
}
}
else{
return false;
}
This throws an error like following
Error: TypeError: $.validationEngine.defaults.rulesArray is undefined
Source File: http://localhost:8380/javascript/jquery.validationEngine.js
Line: 2092
I cannot find the problem with this code.Any help is welcome
EDIT:
I am trying to set the global options eg:scroll using the for loop.
The formRules string will have these options comma seperated and the corresponding values in the formValues string.
So i am expecting it to come like $.validationEngine.defaults.scroll = true;
change this line
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
to this
$.validationEngine.defaults[rulesArray[i]] = valuesArray[i];
rulesArray is not a child of $.validationEngine.defaults. The values stored in your rulesArray are. The syntax in my second code block references everything properly.
This is called Bracket Notation, a way to get an object's property using any sort of valid calculation (like rulesArray[i], or "myStringPropertyName"). see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators for other methods.
Related
I am trying to get links from one page. Here's a simple code to get all links from certain dom element.
var $ = jQuery;
var page = $("#main .entry p");
var rez = [];
for(var i=0; i<page.length;i++) {
var title = $(page[i]).find("a").text();
var info = $(page[i]).text();
var page_url = $(page[i]).find("a").attr("href");
rez.push({
title: title,
page_url: page_url,
info: info
});
}
I am using this code in Chrome browser's console.
Everything works ok. rez array is populated, and I can veryfy it by something like console.table(rez).
Now I am trying to strip certain part from urls collected in previous step by using split
for(var i=0; i<rez.length;i++) {
console.log(rez[i].page_url); // <- this works
console.log(rez[i].page_url.split("http://something...")[1] ); // <- this fails
}
Important note! I am doing it all in one step by copying entire code (rez populating code and rez iterating in order to make split).
And I am getting this error in console:
VM7064:18 Uncaught TypeError: Cannot read property 'split' of undefined
at <anonymous>:18:29
Why??
The split() function is used to split a string into an array of substrings. In split function as parameter you have to put a separator for example:
"http://something...like-this.com/blablabla".split("/");
This will return you an array ["http:", "", "something...like-this.com", "blablabla"]
In your case you try to split by some text "http://something..." and to get the second element of the array [1]. This will return you undefined in all your cases.
My Javascript is like this :
<script type="text/javascript">
var priceJson = '[{"#attributes":{"Code":"SGL","Total":"400000"},"DayPrice":{"Date":"2016-05-26","Rate":"400000"}},{"#attributes":{"Code":"DBL","Total":"200000"},"DayPrice":{"Date":"2016-05-26","Rate":"200000"}}]';
console.log(priceJson);
var priceObject = JSON.parse(priceJson);
console.log(priceObject);
if(priceObject.DayPrice.Rate)
priceObject = [priceObject];
else
priceObject = priceObject;
console.log(priceObject);
var priceJson = JSON.stringify(priceObject);
console.log(priceJson);
var countRoomType = priceObject.length;
for(var i=0; i<countRoomType; i++){
console.log(priceObject[i].DayPrice.Date);
console.log(priceObject[i].DayPrice.Rate);
}
</script>
Demo (See in console) : https://jsfiddle.net/oscar11/wsqdha8w/1/
Variable priceJson has a dynamic value. The value can be one single instance of data or can be an array of data. If the value contains 1 data then I convert into a data array like this:
if(priceObject.DayPrice.Rate)
priceObject = [priceObject];
But, in console there is the following error: TypeError: priceObject.DayPrice is undefined
Any solutions to solve my problem?
Judging by your error message, you need to check the existance of DayPrice also.
if( priceObject.DayPrice && priceObject.DayPrice.Rate )
This if condition has two steps.
First it checks if DayPrice exists,
Second it checks if DayPrice.Rate exists
It won't check second condition if first one fails
I've been having a hard time with cross browser compatibility and scrapping the dom.
I've added data analytics tracking to ecommerce transactions in order to grab the product and transaction amount for each purchase.
Initially I was using document.querySelectorAll('#someId')[0].textContent to get the product name and that was working fine for every browser except internet explorer.
It took some time to figure out that it was the .textContent part that was causing ie problems.
Yesterday I changed .textContent to .innerText. From looking inside analytics it seems that the issue has been resolved for ie but now Firefox is failing.
I was hoping to find a solution without writing an if statement to check for the functionality of .textContent or .innerText.
Is there a cross browser solution .getTheText?
If not what would be the best way around this? Is there a simple solution? (I ask given my knowledge and experience with scripting, which is limited)
** added following comments **
If this is my code block:
// build products object
var prods = [];
var brand = document.querySelectorAll('.txtStayRoomLocation');
var name = document.querySelectorAll('.txtStayRoomDescription');
var price = document.querySelectorAll('.txtStayRoomSplashPriceAmount');
for(var i = 0; i < brand.length; i++) {
//set granular vars
var prd = {};
//add to prd object
prd.brand = brand[i].innerText;
prd.name = name[i].innerText;
prd.price = price[i].innerText;
prd.quantity = window.session_context_vars.BookingContext.Booking.ReservationLineItems[i].ReservationCharges.length/2;;
//add to prods array
prods.push(prd);
}
Then if I understand the syntax from the comments and the question linked to in the comment, is this what I should do:
// build products object
var prods = [];
var brand = document.querySelectorAll('.txtStayRoomLocation');
var name = document.querySelectorAll('.txtStayRoomDescription');
var price = document.querySelectorAll('.txtStayRoomSplashPriceAmount');
for(var i = 0; i < brand.length; i++) {
//set granular vars
var prd = {};
//add to prd object
prd.brand = brand[i].textContent || brand[i].innerText;
prd.name = name[i].textContent || name[i].innerText;
prd.price = price[i].textContent || price[i].innerText;
prd.quantity = window.session_context_vars.BookingContext.Booking.ReservationLineItems[i].ReservationCharges.length/2;;
//add to prods array
prods.push(prd);
}
So using or with a double bar || assigns the first non null value?
Re: your edit, not quite. The way to access methods or properties on an object (eg a DOM element) is to use dot notation if you have the name itself, or square brackets in case of variables/expressions (also works with strings, as in obj["propName"], which is equivalent to obj.propName). You can also just test the property against one element and use that from there on:
// build products object
var prods = [];
var brand = document.querySelectorAll('.txtStayRoomLocation');
var name = document.querySelectorAll('.txtStayRoomDescription');
var price = document.querySelectorAll('.txtStayRoomSplashPriceAmount');
for(var i = 0; i < brand.length; i++) {
//set granular vars
var prd = {};
//add to prd object
var txtProp = ("innerText" in brand[i]) ? "innerText" : "textContent"; //added string quotes as per comments
prd.brand = brand[i][txtProp];
prd.name = name[i][txtProp];
prd.price = price[i][txtProp];
prd.quantity = window.session_context_vars.BookingContext.Booking.ReservationLineItems[i].ReservationCharges.length/2;;
//add to prods array
prods.push(prd);
}
Regarding the line:
var txtProp = (innerText in brand[i]) ? innerText : textContent;
The in keyword checks an object to access the property (syntax: var property in object). As for the question notation (I made an error earlier, using ||, the correct thing to use was a :),
var myVar = (prop in object) ? object[prop] : false;
As an expression, it basically evaluates the stuff before the ?, and if it's true, returns the expression before the :, else the one after. So the above is the same as / a shorthand for:
if(prop in object){
var myVar = object[prop];
}
else{
var myVar = false;
}
Since you are checking between two properties only and wanting to assign one or the other, the shortest way would indeed be:
var txtProp = brand[i].innerText || brand[i].textContent;
It would basically test the first property, and if it were false or undefined, it would use the second one. The only reason I (pedantically) avoid using this is because the first test of a || b would fail even if a existed but just had a value of 0, or an empty string (""), or was set to null.
I imported json data into google scripts with:
var doc = Utilities.jsonParse(txt);
I can access most of the objects like such...
var date = doc.data1.dateTime;
var playerName = doc.data1.playerName;
var playerId = doc.data1.playerID;
var teamNumber = doc.data2.personal.team;
A bunch of objects I need to access have numbers as object names...
doc.data2.personal.team.87397394.otherdata
doc.data2.personal.team.87397395.otherdata
doc.data2.personal.team.87397396.otherdata
doc.data2.personal.team.87397397.otherdata
...but when I try to read the data with...
var teamId = doc.data2.personal.team.87397394;
... I get an error "Missing ; before statement."
I tried this...
var teamId = doc.data2.personal.team[87397394];
... and get "teamId undefined" in the log.
I also tied this with the same result...
var teamId = doc.data2.personal.team[+'6803761'];
I can read in the names as strings very easily with "For In", but can't get to the objects themselves. Every example I've found so far uses the brackets so I'm stumped what to try next.
Thank you!
Brian
UPDATE
I used this per your suggestions to get the object name into a variable and using the variable in brackets. No error but var test remains "undefined"...
for(var propertyName in doc.data2.personal.team) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
Logger.log (propertyNames);
var test = doc.data2.personal.team[propertyName];
}
The log shows the object names, as expected...
87397394
87397395
87397396
87397397
I'm thinking it's a bug in Google's implementation. Here is an example if anyone wants to verify it. test will return undefined...
function myFunction1() {
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = Utilities.jsonParse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
Logger.log (propertyName);
var test = doc.datablock_battle_result.vehicles[propertyName];
}
}
The problem seems to be in the Utitlies.jsonParse. The following works fine
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = JSON.parse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
var vehicle = doc.datablock_battle_result.vehicles[propertyName];
Logger.log('Vehicle id is ' + propertyName);
Logger.log('Vehicle value is ' + JSON.stringify(vehicle));
break;
}
Javascript:
This is my example code below. I use prompt() variables to create string values for each loop.
var team = new Object;
team["fwd"] = "forwards";
for (i=1; i <2+1; i++){
var fwdName = prompt("enter player name");
team["fwd"]["p" + i] = fwdName;
}
It is my understanding with the above that in each loop, I get user input to read in a value for each new property (that is created by ["p"+i]) to be set to. The fwdName variable is overwritten with each loop.
I use the following to check that I actually put in values that can be used;
console.log(team.fwd.p1);
console.log(team.fwd.p2);
and I get undefined as output for each statement.
i belive the fwd property of your main object should be an object not a string.
team["fwd"] = {};