prevent javascript from breaking when xml has an empty node value - javascript

I have example the following xml:
<LOCAL_AUTHORITY>
<NAME>Derby</NAME>
<REGION></REGION>
<IRD>22%</IRD>
<LOCAL_AUTHORITY>
I have the following javascript:
localAuthorities=xmlDoc.getElementsByTagName("LOCAL_AUTHORITY");
alert(localAuthorities[0].getElementsByTagName("REGION")[0].childNodes[0].nodeValue);
alert('This get triggered so javascript is not broken');
My question is that the javascript breaks unless you give region a value in the xml. Kind reagrds to any responders.. how do i prevent it from breaking?

You need to make sure there is something there before you read it. basic idea:
var nodes = localAuthorities[0].getElementsByTagName("REGION")[0].childNodes;
var value = nodes.length===1 ? nodes[0].nodeValue : "";
alert(value);

You can do :
localAuthorities=xmlDoc.getElementsByTagName("LOCAL_AUTHORITY");
// validate if there is region or not
if (localAuthorities[0].getElementsByTagName("REGION")[0].val()){
alert(localAuthorities[0].getElementsByTagName("REGION")[0].childNodes[0].nodeValue);
alert('This get triggered so javascript is not broken');
}

Related

Extract an Page Variant Value with Javascript

I am not a javascript expert at all and expect this to be a fairly simple task.
I am trying to grab the value from a hidden field on my page called pageVariant so I can store it as a value inside of Google Tag Manager. I just don't know how to write the javascript.
This is the code I have tried, but know it is not right. Any help here would be appreciated.
function() {
var capturedText = document.querySelector("#lp-pom-form-162 > form > input[type=hidden]:nth-child(2)");
return capturedText; }
First of all provide a name to your function.
Then use the code mentioned below:
function inputText() {
var capturedText = document.querySelector("input[name='pageVariant']").value;
return capturedText;
}

How to give a "checkbox onChange event" the calling Input Id (in Xpages)

I have an Xpages Application and I am currently using a checkbox in a repeat control to call an onChange function, I want to parse the calling element/elementID to my Client Side Javascript located in: Events->onChange. My problem is that my Javascript returns undefined when using "this". I tried to parse an object on the Function call but that doesnt seem to be possible in Xpages either.
Javascript Code (probably wont be much help):
var fieldsets = document.querySelectorAll("table.checkboxGroups");
console.log(fieldsets);
console.log("-----------------");
var fieldsetCurrent = fieldsets[0]; //this is where I need the calling elem
console.log(fieldsetCurrent);
console.log("-----------------");
var fieldsetCheckboxes = fieldsetCurrent.getElementsByTagName("input");
console.log(fieldsetCheckboxes);
console.log("-----------------");
for(i=0;fieldsetCheckboxes.length;i++){
var elem = fieldsetCheckboxes[i];
console.log(i + " : " +elem);
elem.setAttribute("checked","");
//elem.checked;
}
If your repeating on notes documents then you could add the documentid to the checkbox as an attribute and use this id to call your onChange eventhandler. dojo.query might also be of some value here.

What does "uncaught exception: out of memory" mean and how do you track the cause? [duplicate]

I am debugging a javascript/html5 web app that uses a lot of memory. Occasionally I get an error message in the console window saying
"uncaught exception: out of memory".
Is there a way for me to gracefully handle this error inside the app?
Ultimately I need to re-write parts of this to prevent this from happening in the first place.
You should calclulate size of your localStorage,
window.localStorage is full
as a solution is to try to add something
var localStorageSpace = function(){
var allStrings = '';
for(var key in window.localStorage){
if(window.localStorage.hasOwnProperty(key)){
allStrings += window.localStorage[key];
}
}
return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
};
var storageIsFull = function () {
var size = localStorageSpace(); // old size
// try to add data
var er;
try {
window.localStorage.setItem("test-size", "1");
} catch(er) {}
// check if data added
var isFull = (size === localStorageSpace());
window.localStorage.removeItem("test-size");
return isFull;
}
I also got the same error message recently when working on a project having lots of JS and sending Json, but the solution which I found was to update input type="submit" attribute to input type="button". I know there are limitations of using input type="button"..> and the solution looks weird, but if your application has ajax with JS,Json data, you can give it a try. Thanks.
Faced the same problem in Firefox then later I came to know I was trying to reload a HTML page even before setting up some data into local-storage inside if loop. So you need to take care of that one and also check somewhere ID is repeating or not.
But same thing was working great in Chrome. Maybe Chrome is more Intelligent.

CQ5 AEM: how to get a component by name within a dialog using javascript

I know this will probably a simple question, but I'm new to CQ5 and AEM in general.
I have a cq:Widget node which is a simple textfield.
<rowtitlevalue
jcr:primaryType="cq:Widget"
fieldLabel="Row Title Value"
name="./rowtitlevalue"
xtype="textfield"
disabled="true"/>
Now at the moment within my JavaScript, I'm currently accessing it via
var textfield = panel.findByType('textfield')[1];
which works fine (there's another textfield before this one, hence the 1 in the array.
MY QUESTION:
how do I look for this field using it's NAME attribute within my javascript.
Any help would be appreciated.
Also, I'm using this object to run the following:
if (show != undefined) {
textfield.enable();
textfield.show();
}
else if (show == undefined) {
textfield.disable();
textfield.hide();
}
The JavaScript is located within the Component Based ClientLibs.
And this is the Listener that I have under the checkbox that defines the value of SHOW within the javascript (which is working fine).
<listeners
jcr:primaryType="nt:unstructured"
loadcontent="function(field,rec,path){Ejst.toggleRowTitle(field);}"
selectionchanged="function(field,value){Ejst.toggleRowTitle(field);}"/>
Please let me know if you see any problems with this.
Appreciate it in advance
The CQ.Dialog API defines the getField( String name) method which returns a field with the given name. In case more than one field with the same name exists, it returns an array of those fields.
Thus finding parent of xtype dialog instead of panel as shown below would solve this.
Ejst.toggleRowTitle = function(checkbox) {
var dlg = checkbox.findParentByType('dialog');
var rowTitleField = dlg.getField('./rowtitlevalue');
// perform required operation on rowTitleField
}
i did something like that a few days ago and my solution was to make a js file on the same level of the component and with the same name of the component with the information that i need.
Something like this:
The file will be called rowtitlevalue.js and the content would be:
"use strict";
use(function() {
var data = {};
data.rowtitlevalueData = properties.get("rowtitlevalue");
//more properties if needed...
return {
data: data
}
});
then where i need to use it in javascript, i need the following tags:
<sly data-sly-use.data="rowtitlevalue.js">
<script type="text/javascript">
var myVariable = ${data.rowtitlevalueData};
</script>
</sly>

Taking Data from Form to collection in Backbone

I am having a very big form which has lot of form columns.
I am putting my form data using this code :
var formData = {};
$("#newwaitlist div").children().each(function(i, el){
formData[el.id] = $(el).val();
});
var waitdriver= new DriverWaitModel(formData);
console.log(JSON.stringify(waitdriver));
this.collection.add(waitdriver);
The data is correctly getting taken.
but i am having a small bug in this.
Inside my form i also have my buttons and also form that takes options(like drop downs).
The above code also logs the button value and its id. Is there a way to remove it before adding to the collection ??
IS the way i am passing my data to the collection correct ?? or is there a better way of doing the same ??
Note
I cannot use backbone-stickit or anyother .. Just with backbone, underscore and jquery we have to do. So ...
You could just do a check for the type, as in el.prop('type'). Like this:
$("#newwaitlist div").children().each(function(i, el) {
if (el.prop('type') !== 'button') {
formData[el.id] = $(el).val();
}
});
The above answer also solved the problem,
But in my case i had also to filter out some form elements that were also of not button type.
So this is how i made it work;
if(el.id!="addDriveBtn"===true){
formData[el.id] = $(el).val();
}
which ever id you dont want to input you can just filter out.
Worked great...
JavaScript and Backbone just rocks

Categories