ASP.NET referencing a javascript function - javascript

I have an ASP.NET page, written in VB.NET, that I'm trying to use javascript on. The script takes the value from one listbox and inserts it into another list box. I'm using a master page, which I'm pretty sure is the issue.
Here's the javascript:
function OT_transferLeft() { moveSelectedOptions(this.right, this.left, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_transferRight() { moveSelectedOptions(this.left, this.right, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_transferAllLeft() { moveAllOptions(this.right, this.left, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_transferAllRight() { moveAllOptions(this.left, this.right, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_saveRemovedLeftOptions(f) { this.removedLeftField = f; }
function OT_saveRemovedRightOptions(f) { this.removedRightField = f; }
function OT_saveAddedLeftOptions(f) { this.addedLeftField = f; }
function OT_saveAddedRightOptions(f) { this.addedRightField = f; }
function OT_saveNewLeftOptions(f) { this.newLeftField = f; }
function OT_saveNewRightOptions(f) { this.newRightField = f; }
function OT_update() {
var removedLeft = new Object();
var removedRight = new Object();
var addedLeft = new Object();
var addedRight = new Object();
var newLeft = new Object();
var newRight = new Object();
for (var i = 0; i < this.left.options.length; i++) {
var o = this.left.options[i];
newLeft[o.value] = 1;
if (typeof (this.originalLeftValues[o.value]) == "undefined") {
addedLeft[o.value] = 1;
removedRight[o.value] = 1;
}
}
for (var i = 0; i < this.right.options.length; i++) {
var o = this.right.options[i];
newRight[o.value] = 1;
if (typeof (this.originalRightValues[o.value]) == "undefined") {
addedRight[o.value] = 1;
removedLeft[o.value] = 1;
}
}
if (this.removedLeftField != null) { this.removedLeftField.value = OT_join(removedLeft, this.delimiter); }
if (this.removedRightField != null) { this.removedRightField.value = OT_join(removedRight, this.delimiter); }
if (this.addedLeftField != null) { this.addedLeftField.value = OT_join(addedLeft, this.delimiter); }
if (this.addedRightField != null) { this.addedRightField.value = OT_join(addedRight, this.delimiter); }
if (this.newLeftField != null) { this.newLeftField.value = OT_join(newLeft, this.delimiter); }
if (this.newRightField != null) { this.newRightField.value = OT_join(newRight, this.delimiter); }
}
function OT_join(o, delimiter) {
var val; var str = "";
for (val in o) {
if (str.length > 0) { str = str + delimiter; }
str = str + val;
}
return str;
}
function OT_setDelimiter(val) { this.delimiter = val; }
function OT_setAutoSort(val) { this.autoSort = val; }
function OT_setStaticOptionRegex(val) { this.staticOptionRegex = val; }
function OT_init(theform) {
this.form = theform;
if (!theform[this.left]) { alert("OptionTransfer init(): Left select list does not exist in form!"); return false; }
if (!theform[this.right]) { alert("OptionTransfer init(): Right select list does not exist in form!"); return false; }
this.left = theform[this.left];
this.right = theform[this.right];
for (var i = 0; i < this.left.options.length; i++) {
this.originalLeftValues[this.left.options[i].value] = 1;
}
for (var i = 0; i < this.right.options.length; i++) {
this.originalRightValues[this.right.options[i].value] = 1;
}
if (this.removedLeftField != null) { this.removedLeftField = theform[this.removedLeftField]; }
if (this.removedRightField != null) { this.removedRightField = theform[this.removedRightField]; }
if (this.addedLeftField != null) { this.addedLeftField = theform[this.addedLeftField]; }
if (this.addedRightField != null) { this.addedRightField = theform[this.addedRightField]; }
if (this.newLeftField != null) { this.newLeftField = theform[this.newLeftField]; }
if (this.newRightField != null) { this.newRightField = theform[this.newRightField]; }
this.update();
}
// -------------------------------------------------------------------
// OptionTransfer()
// This is the object interface.
// -------------------------------------------------------------------
function OptionTransfer(l, r) {
this.form = null;
this.left = l;
this.right = r;
this.autoSort = true;
this.delimiter = ",";
this.staticOptionRegex = "";
this.originalLeftValues = new Object();
this.originalRightValues = new Object();
this.removedLeftField = null;
this.removedRightField = null;
this.addedLeftField = null;
this.addedRightField = null;
this.newLeftField = null;
this.newRightField = null;
this.transferLeft = OT_transferLeft;
this.transferRight = OT_transferRight;
this.transferAllLeft = OT_transferAllLeft;
this.transferAllRight = OT_transferAllRight;
this.saveRemovedLeftOptions = OT_saveRemovedLeftOptions;
this.saveRemovedRightOptions = OT_saveRemovedRightOptions;
this.saveAddedLeftOptions = OT_saveAddedLeftOptions;
this.saveAddedRightOptions = OT_saveAddedRightOptions;
this.saveNewLeftOptions = OT_saveNewLeftOptions;
this.saveNewRightOptions = OT_saveNewRightOptions;
this.setDelimiter = OT_setDelimiter;
this.setAutoSort = OT_setAutoSort;
this.setStaticOptionRegex = OT_setStaticOptionRegex;
this.init = OT_init;
this.update = OT_update;
}
var lb1 = document.getElementById("<%=lbSiteType.ClientID%>");
var lb2 = document.getElementById("<%=lbSelectedSiteType.ClientID%>");
var opt = new OptionTransfer(lb1, lb2);
alert(opt);
opt.setAutoSort(true);
opt.setDelimiter(",");
opt.setStaticOptionRegex("^(Bill|Bob|Matt)$");
opt.saveRemovedLeftOptions("removedLeft");
opt.saveRemovedRightOptions("removedRight");
opt.saveAddedLeftOptions("addedLeft");
opt.saveAddedRightOptions("addedRight");
opt.saveNewLeftOptions("newLeft");
opt.saveNewRightOptions("newRight");
and here's the code from the control:
<asp:Button ID="btnMoveAll" Text=" >> " CssClass="button7" CausesValidation="false"
ONCLICK="opt.transferRight()"
runat="server" /><br />
In short, it doesn't work. I keep getting an 'opt' is not a member of the page. Can someone explain how I can properly call this code?

To invoke client Methods(javascript) use OnClientClick
<asp:Button ID="btnMoveAll" Text="" CssClass="button7" CausesValidation="false"
OnClientClick="opt.transferRight()"
runat="server" />

Related

Get a value of a HashTable

I was making a HashTable to have as an example and have it saved for any problem, but I ran into a problem trying to implement a method that returns true or false in case the value belongs to the HashTable, since it is inside a arrays of objects as comment in the code.
I have tried for loops, .map and for of, but it always fails, if someone could help me.
function HashTable () {
this.buckets = [];
this.numbuckets = 35;
}
HashTable.prototype.hash = function (key) {
let suma = 0;
for (let i = 0; i < key.length; i++) {
suma = suma + key.charCodeAt(i);
}
return suma % this.numbuckets;
}
HashTable.prototype.set = function (key, value) {
if (typeof key !== "string") {
throw new TypeError ("Keys must be strings")
} else {
var index = this.hash(key);
if(this.buckets[index] === undefined) {
this.buckets[index] = {};
}
this.buckets[index][key] = value;
}
}
HashTable.prototype.get = function (key) {
var index = this.hash(key);
return this.buckets[index][key];
}
HashTable.prototype.hasKey = function (key) {
var index = this.hash(key);
return this.buckets[index].hasOwnProperty(key)
}
HashTable.prototype.remove = function (key) {
var index = this.hash(key);
if (this.buckets[index].hasOwnProperty(key)) {
delete this.buckets[index]
return true;
}
return false;
}
HashTable.prototype.hasValue = function (value) {
let result = this.buckets;
result = result.flat(Infinity);
return result // [{Name: Toni}, {Mame: Tino}, {Answer: Jhon}]
}
You can use Object.values() to get the values of all the propertyies in the bucket.
function HashTable() {
this.buckets = [];
this.numbuckets = 35;
}
HashTable.prototype.hash = function(key) {
let suma = 0;
for (let i = 0; i < key.length; i++) {
suma = suma + key.charCodeAt(i);
}
return suma % this.numbuckets;
}
HashTable.prototype.set = function(key, value) {
if (typeof key !== "string") {
throw new TypeError("Keys must be strings")
} else {
var index = this.hash(key);
if (this.buckets[index] === undefined) {
this.buckets[index] = {};
}
this.buckets[index][key] = value;
}
}
HashTable.prototype.get = function(key) {
var index = this.hash(key);
return this.buckets[index][key];
}
HashTable.prototype.hasKey = function(key) {
var index = this.hash(key);
return this.buckets[index].hasOwnProperty(key)
}
HashTable.prototype.remove = function(key) {
var index = this.hash(key);
if (this.buckets[index].hasOwnProperty(key)) {
delete this.buckets[index]
return true;
}
return false;
}
HashTable.prototype.hasValue = function(value) {
return this.buckets.some(bucket => Object.values(bucket).includes(value));
}
let h = new HashTable;
h.set("Abc", 1);
h.set("Def", 2);
console.log(h.hasValue(1));
console.log(h.hasValue(3));

JavaScript: multiple instances wrong reference to private property

In the fiddle is a "class" I have written to manage navigation over the data model and a test which shows that multiple instances (starting from second) of this "class" are referencing something wrong.
https://jsfiddle.net/btvmnaxc/
(outputs to console)
Expected output would be
[{"name":"xx"}]
[{"name":"yy"}]
But after setting Elements via setElements, in other methods Elements is empty, strangely only after creating the second instance. I could think that setElements overwrites the reference, but why other methods keep this old reference instead of getting a new one from the var.
Could somebody explain this behavior?
P.S. I probably can think on a solution, as packing vars in a property which is an object.
function Pagination() {
var props = {Elements:[], ...}
}
P.S.S
function Pagination() {
var that = this;
var Elements = [0,1];
var Frame = [];
var FrameNumber = 0;
var EntitiesPerFrame = 25;
var FrameChangedCB = [];
this.subscribeFrameChange = function(cb) {
if (typeof cb === "function") {
FrameChangedCB.push(cb);
} else {
throw new Error("Not a function");
}
}
this.setEntitiesPerFrame = function(entities_per_frame) {
entities_per_frame = parseInt(entities_per_frame);
if (entities_per_frame > 0) {
EntitiesPerFrame = entities_per_frame;
while (!this.canDisplayFrame(FrameNumber) && FrameNumber > 0) {
FrameNumber--;
}
calculateFrame();
}
}
frameChanged = function() {
FrameChangedCB.forEach(function(cb) {
cb();
});
}
this.setElements = function(elements) {
if (Array.isArray(elements)) {
Elements = elements;
calculateFrame();
console.log("qq");
} else {
throw new Error("Can only work with arrays");
}
}
this.getStart = function() {
return FrameNumber * EntitiesPerFrame;
}
this.getEnd = function() {
var end = (FrameNumber + 1) * EntitiesPerFrame;
return end > Elements.length ? Elements.length : end;
}
this.getEntitiesPerFrame = function() {
return EntitiesPerFrame;
}
calculateFrame = function() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
this.canDisplayFrame = function(nr) {
nr = parseInt(nr);
var can = false;
var start = nr * EntitiesPerFrame
var end = (nr + 1) * EntitiesPerFrame;
if (start <= Elements.length && nr >= 0) {
can = true;
}
return can;
}
this.getFrame = function() {
return Frame;
}
this.next = function() {
return this.goto(FrameNumber + 1);
}
this.prev = function() {
return this.goto(FrameNumber - 1);
}
this.goto = function(frame_nr) {
var changed = false;
if (that.canDisplayFrame(frame_nr)) {
FrameNumber = parseInt(frame_nr);
calculateFrame();
changed = true;
}
return changed;
}
this.getLength = function() {
return Elements.length;
}
}
var b = new Pagination();
var a = new Pagination();
a.setElements([{name: 'xx'}]);
b.setElements([{name: 'yy'}]);
console.log(JSON.stringify(a.getFrame()));
console.log(JSON.stringify(b.getFrame()));
This is happening because you are abusing implicit globals.
Your Pagination function contains two places where a function is assigned to an identifier without using var:
calculateFrame = function() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
This will assign this function to a global variable named calculateFrame and any call to calculateFrame() will be calling whichever of those was assigned last (and therefore be using whatever scope it has access to).
To fix this, use var:
var calculateFrame = function() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
Or better yet, use a named function declaration:
function calculateFrame() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
After fixing the two places where you have this issue, the snippet outputs the expected result.
function Pagination() {
var that = this;
var Elements = [0, 1];
var Frame = [];
var FrameNumber = 0;
var EntitiesPerFrame = 25;
var FrameChangedCB = [];
this.subscribeFrameChange = function(cb) {
if (typeof cb === "function") {
FrameChangedCB.push(cb);
} else {
throw new Error("Not a function");
}
}
this.setEntitiesPerFrame = function(entities_per_frame) {
entities_per_frame = parseInt(entities_per_frame);
if (entities_per_frame > 0) {
EntitiesPerFrame = entities_per_frame;
while (!this.canDisplayFrame(FrameNumber) && FrameNumber > 0) {
FrameNumber--;
}
calculateFrame();
}
}
function frameChanged() {
FrameChangedCB.forEach(function(cb) {
cb();
});
}
this.setElements = function(elements) {
if (Array.isArray(elements)) {
Elements = elements;
calculateFrame();
console.log("qq");
} else {
throw new Error("Can only work with arrays");
}
}
this.getStart = function() {
return FrameNumber * EntitiesPerFrame;
}
this.getEnd = function() {
var end = (FrameNumber + 1) * EntitiesPerFrame;
return end > Elements.length ? Elements.length : end;
}
this.getEntitiesPerFrame = function() {
return EntitiesPerFrame;
}
function calculateFrame() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
this.canDisplayFrame = function(nr) {
nr = parseInt(nr);
var can = false;
var start = nr * EntitiesPerFrame
var end = (nr + 1) * EntitiesPerFrame;
if (start <= Elements.length && nr >= 0) {
can = true;
}
return can;
}
this.getFrame = function() {
return Frame;
}
this.next = function() {
return this.goto(FrameNumber + 1);
}
this.prev = function() {
return this.goto(FrameNumber - 1);
}
this.goto = function(frame_nr) {
var changed = false;
if (that.canDisplayFrame(frame_nr)) {
FrameNumber = parseInt(frame_nr);
calculateFrame();
changed = true;
}
return changed;
}
this.getLength = function() {
return Elements.length;
}
}
var b = new Pagination();
var a = new Pagination();
a.setElements([{
name: 'xx'
}]);
b.setElements([{
name: 'yy'
}]);
console.log(a.getFrame());
console.log(b.getFrame());

Hashing: Separate chaining with linked list in javascript

/*****************************************************
LIST
*****************************************************/
function Node(element) {
// store the node's data
this.element = element;
// store a link to the next node in the linked list
this.next = null;
}
function LList() {
this.head = new Node("head");
this.find = find;
this.insert = insert;
this.display = display;
this.findPrevious = findPrevious;
this.remove = remove;
}
function find(item) {
var currNode = this.head;
while(currNode.element != item) {
currNode = currNode.next;
}
return currNode;
}
function insert(newElement) {
var newNode = new Node(newElement);
var current = this.find("head");
newNode.next = current.next;
current.next = newNode;
}
function display(list) {
var currNode = this.head.next;
while (currNode != null) {
console.log(currNode.element);
currNode = currNode.next;
}
}
function findPrevious(item) {
var currNode = this.head;
while((currNode.next != null) && (currNode.next.element != item)) {
currNode = currNode.next;
}
return currNode;
}
function remove(item) {
var prevNode = this.findPrevious(item);
if (prevNode.next != null) {
prevNode.next = prevNode.next.next;
}
}
/*****************************************************
Hash Table
*****************************************************/
function HashTable() {
this.table = new Array(137);
this.betterHash = betterHash;
this.showDistro = showDistro;
this.put = put;
this.get = get;
this.buildChains = buildChains;
}
function put(key) {
var pos = this.betterHash(key);
this.table[pos].insert(key);
}
function get(key) {
var pos = this.betterHash(key);
return this.table[pos].find(key).element;
}
function betterHash(key) {
var constant = 37;
var total = 0;
for (var i = 0; i < key.length; i++) {
total += constant * total + key.charCodeAt(i);
}
total = total % this.table.length;
if(total < 0) {
total += this.table.length - 1;
}
return parseInt(total, 10);
}
function showDistro() {
for(var i = 0; i < this.table.length; i++) {
var currNode = this.table[i].head.next;
while (currNode != null) {
console.log(currNode.element);
currNode = currNode.next;
}
}
}
function buildChains() {
for (var i = 0; i < this.table.length; i++) {
this.table[i] = new LList();
}
}
var hTable = new HashTable();
hTable.buildChains();
var someNames = ["David", "Jennifer", "Donnie", "Raymond",
"Cynthia", "Mike", "Clayton", "Danny", "Jonathan"];
for(var i = 0; i < someNames.length; i++) {
hTable.put(someNames[i]);
}
hTable.showDistro();
hTable.get("David"); // "David"
I built a separate chaining by using both linked list and hash table in javascript. I was reading this book "Data structure and algorithm in javascript". But this author made a lot of mistakes and I think he doesn't really know about javascript. I modified his codes a lot. But since JavaScript is my first programming language and also this is my first time to learn data structure and algorithm, so I am not sure if I build it right.
Please explain how to modify or rebuild these codes again!

Cannot read property `attachEvent` of null

I have a JavaScript file using speechSynthesis.
I keep having this error:
"Cannot read property 'attachEvent' of null" in line 129:
Here it is:
speech.bind = function(event, element, callback) {
**if (element.attachEvent) {**
element.attachEvent('on'+event, callback )
} else if (window.addEventListener) {
element.addEventListener(event, callback ,false);
};
};
I will put in here the role code in here so anyone can check the entire JavaScript:
var speech_def = speech_def || {
container: "#glb-materia"
,insert_before: true
,ico: "http://edg-1-1242075393.us-east-1.elb.amazonaws.com/speech/listen_icon.jpg"
,bt_txt: "OUÇA A REPORTAGEM"
,bt_stop: "PARAR!"
,source: ".materia-conteudo"
,ignore: [
".foto-legenda"
,".frase-materia"
,"script"
,"style"
,"#speech"
,".sub-header"
,".chamada-materia"
,".data-autor"
,".box-tags"
,".saibamais"
]
};
var speech = speech || {};
//Polyfill remove()
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
};
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for (var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
};
//Polyfill innerText
if ( (!('innerText' in document.createElement('a'))) && ('getSelection' in window) ) {
HTMLElement.prototype.__defineGetter__("innerText", function() {
var selection = window.getSelection(),
ranges = [],
str;
for (var i = 0; i < selection.rangeCount; i++) {
ranges[i] = selection.getRangeAt(i);
}
selection.removeAllRanges();
selection.selectAllChildren(this);
str = selection.toString();
selection.removeAllRanges();
for (var i = 0; i < ranges.length; i++) {
selection.addRange(ranges[i]);
}
return str;
})
}
speech.iOS = /(iPad|iPhone|iPod)/g.test( navigator.userAgent );
speech.Android = /(Android)/g.test( navigator.userAgent );
speech.include = function() {
var bt = ""
bt += '<div id="speech" '
+'title="'+speech_def.bt_txt+'" '
+'style="'
+'display: none; '
+'margin: 5px; '
+'font-size: 12px; '
+'font-style: italic; '
+'color: #bbbbbb; '
+'cursor: pointer;"'
+'>';
bt += '<img style="width: 25px; height: 25px;" src="'+speech_def.ico+'"> ';
bt += '<i style="vertical-align: top; line-height: 28px;">'+speech_def.bt_txt+'</i>';
bt += '</div>';
var button = document.createElement("SPAN");
button.innerHTML = bt;
var box = document.querySelectorAll(speech_def.container)[0];
if (speech_def.insert_before) {
box.insertBefore(button,box.firstChild);
} else {
box.appendChild(button)
};
};
speech.stop = function() {
window.speechSynthesis.cancel();
}
speech.stop();
speech.content = function() {
var result = "";
var boxes = speech_def.source.split(",");
boxes.reverse();
for (var n = boxes.length - 1; n >= 0; n--) {
var doc = document.querySelector(boxes[n]);
if (doc) {
doc = doc.cloneNode(true);
for (var i = speech_def.ignore.length - 1; i >= 0; i--) {
var els = doc.querySelectorAll(speech_def.ignore[i]);
for (var j = els.length - 1; j >= 0; j--) {
els[j].remove();
};
};
result += "." + doc.innerText;
};
};
return result;
};
speech.start_speech = function() {
var content = speech.content();
// Note: some voices don't support altering params
if (!speech.Android) speech.msg.voice = speech.voices[0];
// msg.voiceURI = 'native';
speech.msg.volume = speech.iOS?1:1; // 0 to 1
speech.msg.rate = speech.iOS?0.6:1; // 0.1 to 10
speech.msg.pitch = speech.iOS?1:1; // 0 to 2
speech.msg.text = content;
speech.msg.lang = 'pt-BR';
speech.msg.onend = function(e) {
// console.log('Finished in ' + event.elapsedTime + ' seconds.');
};
window.speechSynthesis.speak(speech.msg);
};
speech.read = function(){}; //chrome problem
speech.bind = function(event, element, callback) {
if (element.attachEvent) {
element.attachEvent('on'+event, callback )
} else if (window.addEventListener) {
element.addEventListener(event, callback ,false);
};
};
speech.click = function(e){
event.stopPropagation()
if (window.event) window.event.cancelBubble = true;
var control = document.getElementById("speech");
var label;
if (window.speechSynthesis.speaking) {
label = speech_def.bt_txt;
speech.stop();
} else {
label = speech_def.bt_stop;
speech.start_speech();
};
control.querySelector("i").innerHTML = label;
}
speech.bind_button = function() {
var control = document.getElementById("speech");
speech.bind("click",control,speech.click);
};
speech.show_button = function() {
if (!speech.on_page) {
speech.on_page = true;
speech.include();
speech.bind_button();
};
var control = document.getElementById("speech");
control.style.display="inline-block";
};
speech.test_portuguese = function() {
speech.voices = [];
window.speechSynthesis.getVoices().forEach(function(voice) {
if (voice.lang == "pt-BR") {
speech.voices.push(voice);
};
});
if (speech.Android) {
var control = document.getElementById("speech");
var complement = (speech.voices.length > 0)?"*":"";
// control.querySelector("i").innerHTML = "OUÇA A REPORTAGEM"+complement;
return true;
} else {
return (speech.voices.length > 0);
};
};
speech.start = function() {
if ('speechSynthesis' in window) {
speech.msg = new SpeechSynthesisUtterance();
if (speech.test_portuguese()) {
speech.show_button();
} else {
window.speechSynthesis.onvoiceschanged = function() {
if (speech.test_portuguese()) {
speech.show_button();
};
};
};
speech.bind_button();
};
};
speech.start();
speech.bind("load",window,speech.start)
How can i solve this problem?
Thanks so much.
The problem is that element is null at that point.
Probably, because there is no element with id="speech", so control in null in this code:
speech.bind_button = function() {
var control = document.getElementById("speech");
speech.bind("click",control,speech.click);
};

XML Javascript undefined error in ie9

I have a 'jargon buster' on my site that uses an xml file to load an A-Z of words which when clicked display a brief short explanation of each word. This works fine in all browsers bar the latest ie's which i get an 'undefined' error with. The jscript im using is below
Jargon = {
xmlfile: 'http://www.mysite.com/jargon.xml',
xml: null,
wordHolder: 'words',
defHolder: 'definition',
idprefix: 'jargon_',
selected: null,
init: function () {
var con = Jargon.xhcon();
Jargon.wordHolder = $(Jargon.wordHolder);
Jargon.defHolder = $(Jargon.defHolder);
if (!con || !Jargon.wordHolder || !Jargon.defHolder) {
return;
}
function conComplete(oXML) {
Jargon.xml = oXML.responseXML;
//Jargon.showWords('a');
}
con.connect(Jargon.xmlfile, 'GET', Math.random(), conComplete);
},
showWords: function (c) {
if (Jargon.selected) {
Jargon.selected.className = '';
}
var words = Jargon.getWords(c);
while (Jargon.wordHolder.childNodes.length > 0) {
Jargon.wordHolder.removeChild(Jargon.wordHolder.childNodes[0]);
}
while (Jargon.defHolder.childNodes.length > 0) {
Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
}
for (var i = 0; i < words.length; i++) {
var o = document.createElement('a');
o.href = 'javascript:Jargon.showDef(\'' + words[i].id + '\');';
o.id = Jargon.idprefix + words[i].id;
//o.onclick = Jargon.showDef;
o.appendChild($t(words[i].name));
Jargon.wordHolder.appendChild(o);
Jargon.wordHolder.appendChild(document.createElement('br'));
}
if (!words.length) {
var o = document.createElement('p');
var s = 'There are no words for the letter ' + c.toUpperCase();
Jargon.wordHolder.appendChild(o.appendChild($t(s)));
}
},
showDef: function (id) {
var o = $(Jargon.idprefix + id);
if (Jargon.selected) {
Jargon.selected.className = '';
}
if (o) {
o.className = 'selected';
Jargon.selected = o;
}
var defobjs = Jargon.getDef(id);
while (Jargon.defHolder.childNodes.length > 0) {
Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
}
var heading = document.createElement('span');
heading.className = "jargtitle";
heading.appendChild(document.createTextNode(defobjs[1][0].textContent));
Jargon.defHolder.appendChild(heading);
var definition = document.createElement('span');
definition.className = "jargdefinition";
definition.appendChild(document.createTextNode(defobjs[0][0].textContent));
Jargon.defHolder.appendChild(definition);
},
getWords: function(c) {
var x = Jargon.xml;
var letters = x.getElementsByTagName('letter');
var oLetter = null;
for (var i = 0; i < letters.length; i++) {
if (letters[i].getAttribute('id') == c) {
oLetter = letters[i];
break;
}
}
if (!oLetter) {
return [];
}
var words = [];
for (i = 0; i < oLetter.childNodes.length; i++) {
var oJargon = oLetter.childNodes[i];
if (oJargon.nodeName == 'jargon') {
var s = Jargon.getName(oJargon);
words[words.length] = {
id: oLetter.childNodes[i].getAttribute('id'),
name: s
};
}
}
return words;
},
getDef: function (id) {
var x = Jargon.xml;
var j = null;
var temp = new Array(2);
var jargons = x.getElementsByTagName('jargon');
for (var i = 0; i < jargons.length; i++) {
if (jargons[i].getAttribute('id') == id) {
j = jargons[i];
break;
}
}
if (!j) {
return [];
}
//return [];
for (i = 0; i < j.childNodes.length; i++) {
if (j.childNodes[i].nodeName == 'name') {
temp[1] = j.childNodes[i].childNodes;
}
}
for (i = 0; i < j.childNodes.length; i++) {
if (j.childNodes[i].nodeName == 'desc') {
temp[0] = j.childNodes[i].childNodes;
}
}
//return [];
return temp;
},
cloneNode: function (oldNode, deep) {
deep = (deep) ? true : false;
// a replacement to the normal dom clone node
// this will copy xml nodes to html nodes
// which can then be inserted into the document
// scope in all browsers
// See for for the bug http://www.quirksmode.org/blog/archives/2005/12/xmlhttp_notes_c.html
var newNode = null;
if (oldNode.nodeType == '3') {
// textnode
newNode = $t(oldNode.nodeValue);
}
else if (oldNode.nodeType == '1') {
// element node
newNode = document.createElement(oldNode.nodeName);
if (deep) {
for (var i = 0; i < oldNode.childNodes.length; i++) {
newNode.appendChild(Jargon.cloneNode(oldNode.childNodes[i], true));
}
}
}
return newNode;
},
getName: function (oJargon) {
for (var i = 0; i < oJargon.childNodes.length; i++) {
if (oJargon.childNodes[i].nodeName == 'name') {
var oName = oJargon.childNodes[i];
var s = '';
for (var j = 0; j < oName.childNodes.length; j++) {
if (oName.childNodes[j].nodeType == 3) {
// text node
s += oName.childNodes[j].nodeValue;
}
}
return s;
}
}
return '';
},
xhcon: function () {
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) {
return null;
}
this.connect = function(sURL, sMethod, sVars, fnDone) {
if (!xmlhttp) {
return false;
}
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET") {
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else {
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && !bComplete) {
bComplete = true;
fnDone(xmlhttp);
}
};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
}
In terms of how im calling the jscript im using <li>a</li>
which loads a list of all items that begin with f then when i click one of items from that list say "Fiduciary" it triggers javascript:Jargon.showDef('f1'); which in turns loads the and into a definition div
however in ie9 it displays "undefined" . It works in all other browers
Example of the XML below:
<letter id="f"> -<jargon id="f1"> <name>Fiduciary</name> <desc>in a position of trust. This includes people such as trustees looking after trust assets for the beneficiaries and company directors running a company for the shareholders' benefit.</desc> </jargon> -<jargon id="f2"> <name>Forfeiture</name> <desc>the loss of possession of a property because the tenancy conditions have not been met by the tenant.</desc> </jargon> -<jargon id="f3"> <name>Freehold</name> <desc>describing land that only the owner has any rights over.</desc> </jargon> -<jargon id="f4"> <name>Free of encumbrances</name> <desc>no one else having any rights over something. When property is owned by someone and nobody else has any rights over it, it is owned free of encumbrances.</desc> </jargon> </letter>

Categories

Resources