this.xmlDoc.getElementsByClassName is not a function - javascript

Hi im trying to get the score elements from an xmlto then upload to the local storage i have the xml upload as you can see in this image
xmluploaded but when i try to get the elements of Score it appears this error this.xmlDoc.getElementsByClassName is not a function ,i would appreciate the help.
class XML_Database {
constructor () {
this.xmlDoc = null;
}
loadXMLfile(path, callback){
let request = new XMLHttpRequest();
request.open("GET",path,true);
request.setRequestHeader("Content-Type","text/xml");
request.onreadystatechange= function(){
if(request.readyState=== XMLHttpRequest.DONE && request.status==200){
callback(request.responseXML);
}
};
request.send()
}
SearchXML (query, num_scores) {
let Scores = [];
let x = this.xmlDoc.getElementsByClassName(query);
if (num_scores> x.length) {
num_scores= x.length;
}
for (let i = 0; i < num_scores; i++) {
for (let j = 0; j < x[i].childNodes.length; j++) {
if (x[i].childNodes[j].nodeName == "Value") {
Scores.push(x[i].childNodes[j].textContent);
break;
}
}
}
return Scores;
}
setXMLDoc(xmlDoc){
this.xmlDoc = xmlDoc;
}
and this is when i call the methods
set_xml(){
const self = this;
let new_XML_file = "/xml/Scores_Database.xml";
this.XML_db.setXMLDoc(new_XML_file);
this.XML_db.loadXMLfile(new_XML_file,function(xml){
console.log(xml);
self.XML_db.SearchXML("Score", 5) ;
});
}

Related

Removing event listener from a tile of sudoku game

I`m trying to remove event listener from a tile that has been filled correctly on a sudoku game. But it is not working. After i fill the correct number on slot, i wish i wouldnt be able to click it again, but happens as the GIF show, it is erasing the grayed slots, meaning that removeEventListener is not working correctly. Any Help?
function qsa(selector) {
return document.querySelectorAll(selector);
}
function removeListenTiles() {
let tiles = qsa("tile");
for (let i = 0; i < tiles.length; i++) {
if (tiles[i].innerHTML.indexOf("table") == -1) {
if (tiles[i].textContent != "") {
tiles[i].removeEventListener("click", () => handleTile(tile[i), true);
}
}
}
}
function handleTile(tile) {
if (!disableSelect) {
if (tile.classList.contains("selected")) {
removeAllGrayedSelected();
updateMove();
removeSelected(tile);
selectedTile = null;
selectedNum = null;
} else {
removeAllGrayedSelected();
if (tile.innerHTML.indexOf("table") != -1) {
for (let j = 0; j < 81; j++) {
if (qsa(".tile")[j] !== tile) removeSelected(qsa(".tile")[j]);
}
tile.classList.add("selected");
selectedTile = tile;
updateSurround(tile);
updateMove();
}
}
}
}
function addListenTile(tile) {
tile.addEventListener("click", () => handleTile(tile), true);
}
Tried the currying method,and added tile.id to handlers array. Solved the problem.
const handlers = [];
const addListenTile = (tile) => {
tile.addEventListener("click", handlers[tile.id] = handleTile(tile), true);
};
const removeListenTile = (tile) => {
tile.removeEventListener("click", handlers[tile,id], true);
}
const handleTile = function (tile) {
return function onhandlerTile(event) {
console.log("OK1")
if (!disableSelect) {
if (tile.classList.contains("selected")) {
console.log("OK2");
removeAllGrayedSelected();
updateMove();
removeSelected(tile);
selectedTile = null;
selectedNum = null;
} else {
console.log("OK3");
removeAllGrayedSelected();
if (tile.innerHTML.indexOf("table") != -1) {
for (let j = 0; j < 81; j++) {
if (qsa(".tile")[j] !== tile) removeSelected(qsa(".tile")[j]);
}
tile.classList.add("selected");
selectedTile = tile;
updateSurround(tile);
updateMove();
}
}
}
};
};

iframe element returns undefined after onload event?

EDIT: Is there no one who can shed some light on this issue? Anything would be appreciated. :)
I have a script that is supposed to check to see if an elements html contains a given string..
When these elements do exist, my code throws this error: Uncaught TypeError: Cannot read property 'outerHTML' of null
This is the line: let check = document.querySelector("#iframe_${globalI}").contentWindow.document.querySelector(".Row"+inc).outerHTML
I then check to see if the string includes a check string.. IE: check.includes("Pre Trip")
If I run this line directly in the console it works and returns true... So what is going on here..?? How can I get this check to pass..?
I have this check executing after a setTimeout of 20 seconds, then wrapped again in another setTimeout for 500ms as I was trying to figure this out..
Also, I need to note that there are no XSS / CORS issues.
Here is my code..
function checkRowCount(x){
console.log("Row count called on "+x);
let rowCount = 0;
for(let i = 0; i < 30; i++){
if(typeof(document.querySelector(`#iframe_${x}`).contentWindow.document.querySelector('.Row'+i)) != 'undefined' && document.querySelector(`#iframe_${x}`).contentWindow.document.querySelector('.Row'+i) != null){
rowCount++;
}
}
console.log(rowCount);
return rowCount;
}
let globalCompiler = []; //globalCompiler[globalI] = {unit: unitNumber[globalI], data: ["X", " ", "NO POST TRIP]}
let unitNumber = [1031,1743,1744,1986,3239,3256,3257,4024,4062,4063,4064,4065,4247,4309,4315,4326,4327,4334,4335,4337,4350,4382,4385,7166,7380,7381,8765,8823,8945,8950,8988,10720,17045,17163,40014,40069,40122,40380,80129,80188,80700,80701,80702,80728,80831,80852,80875,"80876","81027","81038","401288","401306","402409","60099T","CH889","CH890","SR31077","T19","U5509","U6660","U6667","U6675","U8854","US1025T"];
let url = "http://winweb.cleanharbors.com/Vehicle/VehicleTDSearch.aspx?SearchType=DVIR";
function iframeLoaded(selector, unit, setDate, callback){
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtStartDate").value = setDate;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtEndDate").value = setDate;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtVhcleNo").value = unit;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#btnRetrieve").click();
}
let loadFinished = {};
for(let dec = 0; dec < unitNumber.length; dec++){
loadFinished[unitNumber[dec]] = false;
}
console.log(loadFinished);
for(let globalI = 0; globalI < 3; globalI++){
globalCompiler[globalI] = {unit: unitNumber[globalI], data: []};
let iframeObj = document.createElement('iframe');
iframeObj.id = `iframe_${globalI}`;
iframeObj.hidden = false;
iframeObj.src = url;
iframeObj.onload = () => {
if (loadFinished[unitNumber[globalI]] == false) {
loadFinished[unitNumber[globalI]] = true;
let setDate = "11/01/2019";
iframeLoaded(globalI, unitNumber[globalI], setDate);
console.log("iframeloaded called on " + globalI);
setTimeout(() => {
setTimeout(() => {
let dateCheckObject = {}, rowCount = checkRowCount(globalI), trackingArr = [];
if (rowCount == 0) {
globalCompiler[globalI].data.push(" ");
} else {
for (let inc = 1; inc <= rowCount; inc++) {
//let check = $('#iframe_'+globalI).contents().find(`.Row` + inc).html().includes("Pre Trip");
let check = document.querySelector(`#iframe_${globalI}`).contentWindow.document.querySelector(".Row"+inc).outerHTML
if (check.includes("Pre Trip")) {
dateCheckObject.pre = true;
} else {
dateCheckObject.post = true;
}
}
if(dateCheckObject.pre && dateCheckObject.post) {
console.log("X");
globalCompiler[globalI].data.push("X");
dateCheckObject = {};
} else if (dateCheckObject.pre == 'undefined') {
console.log("NO PRE");
globalCompiler[globalI].data.push("NO PRE TRIP");
dateCheckObject = {};
} else {
console.log("NO POST");
globalCompiler[globalI].data.push("NO POST TRIP");
dateCheckObject = {};
}
}
},500);
}, 20000);
}
};
document.body.appendChild(iframeObj);
console.log("Global Loop called");
}
```
A for loop ran one count too far...
e.g.: for (let inc = 1; inc <= rowCount; inc++)
Should have been for (let inc = 1; inc < rowCount; inc++)

Javascript Works on Desktop but only Partially Works on Mobile

The following is the full JavaScript code for a quiz. It works perfectly on desktop browsers. However, when I went to test it on my phone, it doesn't work.
Mobile loads the JSON quiz, but after all the answers are selected, it does not freeze all the selected answers and display the results. Instead, nothing happens, no result is shown/calculated, and the user can continue to select answers.
I'm not experienced with JavaScript on Mobile and don't know what is causing the problem.
I've deleted a few parts of the code that simply appended html in order to cut down on size.
You can view it here: plnkr.co/edit/tkCQVxoIq9oOiApeUY66?p=preview
// Adds the functionality to check if an element has a class
HTMLElement.prototype.hasClass = function (className) {
"use strict";
if (this.classList) {
return this.classList.contains(className);
}
return (-1 < this.className.indexOf(className));
};
// Adds the ability to remove classes from elements
HTMLElement.prototype.removeClass = function (className) {
"use strict";
if (this.classList) {
this.classList.remove(className);
}
return this;
};
var BF_QUIZ = {};
BF_QUIZ.quiz = function () {
"use strict";
// Sets variables
var highest_score, quiz_div, quiz_title, quiz_image, questions = [],
results = [], inputs = [], answers = [], userAnswers = [],
// Gets the Quiz "canvas"
getQuizCanvas = function getQuizCanvas() {
quiz_div = document.getElementById("bf-quiz");
},
// Parses the JSON data passed from the Loader
getJSONData = function getJSONData(json_data) {
//Main Quiz Title
quiz_title = json_data[0].quiz_title;
//Main Quiz Image
quiz_image = json_data[0].quiz_image;
//Populates questions arrary with questions from JSON file
for (var i = 0; i < json_data[0].quiz_questions.length; i++) {
questions.push(json_data[0].quiz_questions[i]);
}
//Populates results array with results from JSON file
for (var j = 0; j < json_data[0].quiz_results.length; j++) {
results.push(json_data[0].quiz_results[j]);
}
},
// Writes the Quiz into the document
writeQuiz = function writeQuiz() {
var newQuizWrapper, newTitle, newQuestionTextWrapper, newQuestionText,
newAnswerForm, newAnswer, newAnswerImage, newAnswerTextWrapper, newAnswerInput,
newAnswerText, newQuestion;
newQuizWrapper = document.createElement("div");
newQuizWrapper.className = "quiz-wrapper";
newTitle = document.createElement("h1");
newTitle.innerHTML = quiz_title;
newQuizWrapper.appendChild(newTitle);
for (var i = 0; i < questions.length; i++) {
newQuestionTextWrapper = document.createElement("div");
newQuestionTextWrapper.className = "quiz-question-text-wrapper";
newQuestionText = document.createElement("h2");
newQuestionText.innerHTML = questions[i].question.text;
newQuestionTextWrapper.appendChild(newQuestionText);
newAnswerForm = document.createElement("form");
for (var j = 0; j < questions[i].question.question_answers.length; j++) {
newAnswer = document.createElement("div");
newAnswer.className = "quiz-answer";
newAnswer.setAttribute("data-quizValue",
questions[i].question.question_answers[j].answer.value);
if (questions[i].question.question_answers[j].answer.image) {
newAnswerImage = document.createElement("img");
newAnswerImage.src = questions[i].question.question_answers[j].answer.image;
newAnswer.appendChild(newAnswerImage);
}
else{
//no image
}
newAnswerTextWrapper = document.createElement("div");
newAnswerTextWrapper.className = "quiz-answer-text-wrapper";
newAnswerTextWrapper.id = "quiz-answer-text-wrapper";
newAnswerInput = document.createElement("input");
newAnswerInput.type = "radio";
newAnswerInput.name = "answer";
inputs.push(newAnswerInput);
newAnswerText = document.createElement("label");
newAnswerText.htmlFor = "quizzer";
newAnswerText.innerHTML = questions[i].question.question_answers[j].answer.text;
newAnswerTextWrapper.appendChild(newAnswerInput);
newAnswerTextWrapper.appendChild(newAnswerText);
newAnswer.appendChild(newAnswerTextWrapper);
answers.push(newAnswer);
newAnswerForm.appendChild(newAnswer);
}
newQuestion = document.createElement("div");
newQuestion.className = "quiz-question";
newQuestion.appendChild(newQuestionTextWrapper);
newQuestion.appendChild(newAnswerForm);
newQuizWrapper.appendChild(newQuestion);
}
quiz_div.appendChild(newQuizWrapper);
},
//Checks all of the inputs to see if the
checkInputs = function checkInputs() {
var c = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
userAnswers.push(inputs[i].parentNode.parentNode.dataset.quizvalue);
c++;
}
}
if (c==questions.length) {
calcResult();
}
},
calcResult = function calcResult() {
var highest = 0;
for (var i = 0; i < results.length; i++) {
results[i].countof = 0;
for (var j = 0; j < userAnswers.length; j++) {
if (userAnswers[j] == results[i].result.id) {
results[i].countof++;
}
}
if (results[i].countof > highest) {
highest = results[i].countof;
highest_score = results[i];
}
}
//disable the inputs after the quiz is finished
writeResult();
disableAnswers();
},
writeResult = function writeResult() {
newResult = document.createElement("div");
//append html to render (quiz result)
...;
quiz_div.appendChild(newResult);
},
updateSelectedAnswer = function updateSelectedAnswer(element) {
element.children.namedItem("quiz-answer-text-wrapper").firstChild.checked = true;
for (var i = 0; i < element.parentNode.children.length; i++) {
if (element.parentNode.children.item(i).hasClass("selected")) {
element.parentNode.children.item(i).removeClass("selected");
}
}
element.className = element.className + " selected";
},
addClickEvents = function addClickEvents() {
var onAnswerClick = function onAnswerClick() {
if (!this.hasAttribute("disabled")) {
updateSelectedAnswer(this);
checkInputs();
}
};
for (var i = 0; i < answers.length; i++) {
answers[i].addEventListener("click", onAnswerClick);
}
},
disableAnswers = function disableAnswers() {
for (var q = 0; q < answers.length; q++) {
answers[q].disabled = true;
answers[q].setAttribute("disabled", true);
answers[q].className = answers[q].className + " disabled";
}
};
return {
init: function (json_data) {
getQuizCanvas();
getJSONData(json_data);
writeQuiz();
addClickEvents();
}
};
}();
BF_QUIZ.quizLoader = function () {
"use strict";
var json_data, request,
loadQuizJSON = function loadQuizJSON(json_url) {
request = new XMLHttpRequest();
request.open("GET", json_url, false);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
json_data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
};
return {
init: function(json_url) {
loadQuizJSON(json_url);
BF_QUIZ.quiz.init(json_data);
}
};
}();
If you ever try to see console log on a mobile device, you might notice that there is a JavaScript error because iOS Safari is less forgiving than whatever desktop browser you use. Particularly it is illegal to set style property of HTMLElement as string in strict mode. You may see examples of the ways to set it properly at https://developer.mozilla.org/en/docs/Web/API/HTMLElement/style If you fix this issue, code seems to be working on Mobile Safari as well.
P.S. note that the offending code is missing in your question and is only visible in the full code of writeResult on plunker. This is why it is so important to provide a Minimal, Complete, and Verifiable example
From your plunker, if you update your code on line 152 from newResultTitle.style = "color:rgba(238,62,52,.99);"; to newResultTitle.style.color = "rgba(238,62,52,.99)"; this would make it work on mobile browsers.
HTMLElement.style reruns a read only property, desktop browser ignoring it when you are trying to assign a value to it, and mobile browser throwing an error.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
Working plunker http://plnkr.co/edit/aVxTP5YCbL94v2GI0IKh?p=preview

Multiple click listeners - java script

I am working on a project that imports some javascript rules from a file myjs.js, which is called (on all the web page of the project) in the header.
This files manages the behavior of checkboxes, and in fact toggling the checks of every checkbox pairs. The problem is that in some case, this behavior is wrong but I can't change anything in this js file because it is too complex.
So, on some page, I decided to listen to the click event on some checkbox to correct the behavior : the problem is that there is a conflict of script and I can't trigger my script (put on this very page). How can I force it to make my java script listened first ?
In fact the checkbox are constructed by myjs.js, applying to the html sequece
<div class="left">
<input type="radio" name="isPubOk" id="pubOk" checked="checked" />
<label for="pubOk"><?php echo _("Oui"); ?></label>
</div>
<div class="left">
<input type ="radio" name="isPubNok" id="pubNok" checked="" />
<label for="pubNok"><?php echo _("Non"); ?></label>
</div>
Here's a sample of the js file :
function initCustomForms() {
getElements();
separateElements();
replaceRadios();
replaceCheckboxes();
replaceSelects();
// hide drop when scrolling or resizing window
if (window.addEventListener) {
window.addEventListener("scroll", hideActiveSelectDrop, false);
window.addEventListener("resize", hideActiveSelectDrop, false);
}
else if (window.attachEvent) {
window.attachEvent("onscroll", hideActiveSelectDrop);
window.attachEvent("onresize", hideActiveSelectDrop);
}
}
function refreshCustomForms() {
// remove prevously created elements
if(window.inputs) {
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked) {checkboxes[i]._ca.className = "checkboxAreaChecked";}
else {checkboxes[i]._ca.className = "checkboxArea";}
}
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked) {radios[i]._ra.className = "radioAreaChecked";}
else {radios[i]._ra.className = "radioArea";}
}
for(var i = 0; i < selects.length; i++) {
var newText = document.createElement('div');
if (selects[i].options[selects[i].selectedIndex].title.indexOf('image') != -1) {
newText.innerHTML = '<img src="'+selects[i].options[selects[i].selectedIndex].title+'" alt="" />';
newText.innerHTML += '<span>'+selects[i].options[selects[i].selectedIndex].text+'</span>';
} else {
newText.innerHTML = selects[i].options[selects[i].selectedIndex].text;
}
document.getElementById("mySelectText"+i).innerHTML = newText.innerHTML;
}
}
}
// getting all the required elements
function getElements() {
// remove prevously created elements
if(window.inputs) {
for(var i = 0; i < inputs.length; i++) {
inputs[i].className = inputs[i].className.replace('outtaHere','');
if(inputs[i]._ca) inputs[i]._ca.parentNode.removeChild(inputs[i]._ca);
else if(inputs[i]._ra) inputs[i]._ra.parentNode.removeChild(inputs[i]._ra);
}
for(i = 0; i < selects.length; i++) {
selects[i].replaced = null;
selects[i].className = selects[i].className.replace('outtaHere','');
selects[i]._optionsDiv._parent.parentNode.removeChild(selects[i]._optionsDiv._parent);
selects[i]._optionsDiv.parentNode.removeChild(selects[i]._optionsDiv);
}
}
// reset state
inputs = new Array();
selects = new Array();
labels = new Array();
radios = new Array();
radioLabels = new Array();
checkboxes = new Array();
checkboxLabels = new Array();
for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
if(document.forms[nf].className.indexOf("default") < 0) {
for(var nfi = 0; nfi < document.forms[nf].getElementsByTagName("input").length; nfi++) {inputs.push(document.forms[nf].getElementsByTagName("input")[nfi]);
}
for(var nfl = 0; nfl < document.forms[nf].getElementsByTagName("label").length; nfl++) {labels.push(document.forms[nf].getElementsByTagName("label")[nfl]);}
for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName("select").length; nfs++) {selects.push(document.forms[nf].getElementsByTagName("select")[nfs]);}
}
}
}
// separating all the elements in their respective arrays
function separateElements() {
var r = 0; var c = 0; var t = 0; var rl = 0; var cl = 0; var tl = 0; var b = 0;
for (var q = 0; q < inputs.length; q++) {
if(inputs[q].type == "radio") {
radios[r] = inputs[q]; ++r;
for(var w = 0; w < labels.length; w++) {
if((inputs[q].id) && labels[w].htmlFor == inputs[q].id)
{
radioLabels[rl] = labels[w];
++rl;
}
}
}
if(inputs[q].type == "checkbox") {
checkboxes[c] = inputs[q]; ++c;
for(var w = 0; w < labels.length; w++) {
if((inputs[q].id) && (labels[w].htmlFor == inputs[q].id))
{
checkboxLabels[cl] = labels[w];
++cl;
}
}
}
}
}
//replacing radio buttons
function replaceRadios() {
for (var q = 0; q < radios.length; q++) {
radios[q].className += " outtaHere";
var radioArea = document.createElement("div");
if(radios[q].checked) {
radioArea.className = "radioAreaChecked";
}
else
{
radioArea.className = "radioArea";
}
radioArea.id = "myRadio" + q;
radios[q].parentNode.insertBefore(radioArea, radios[q]);
radios[q]._ra = radioArea;
radioArea.onclick = new Function('rechangeRadios('+q+')');
if (radioLabels[q]) {
if(radios[q].checked) {
radioLabels[q].className += "radioAreaCheckedLabel";
}
radioLabels[q].onclick = new Function('rechangeRadios('+q+')');
}
}
return true;
}
//checking radios
function checkRadios(who) {
var what = radios[who]._ra;
for(var q = 0; q < radios.length; q++) {
if((radios[q]._ra.className == "radioAreaChecked") && (radios[q]._ra.nextSibling.name == radios[who].name))
{
radios[q]._ra.className = "radioArea";
}
}
what.className = "radioAreaChecked";
}
//changing radios
function changeRadios(who) {
if(radios[who].checked) {
for(var q = 0; q < radios.length; q++) {
if(radios[q].name == radios[who].name) {
radios[q].checked = false;
}
radios[who].checked = true;
checkRadios(who);
}
}
}
//rechanging radios
function rechangeRadios(who) {
if(!radios[who].checked) {
for(var q = 0; q < radios.length; q++) {
if(radios[q].name == radios[who].name) {
radios[q].checked = false;
}
if(radioLabels[q]) {
radioLabels[q].className = radioLabels[q].className.replace("radioAreaCheckedLabel","");
}
}
radios[who].checked = true;
if(radioLabels[who] && radioLabels[who].className.indexOf("radioAreaCheckedLabel") < 0) {
radioLabels[who].className += " radioAreaCheckedLabel";
}
checkRadios(who);
if(window.$ && window.$.fn) {
$(radios[who]).trigger('change');
}
}
}
//replacing checkboxes
function replaceCheckboxes() {
if (replaceCheckBoxes == 0)
return;
for (var q = 0; q < checkboxes.length; q++) {
// checkboxes[q].className += " outtaHere";
var checkboxArea = document.createElement("div");
if(checkboxes[q].checked) {
checkboxArea.className = "checkboxAreaChecked";
if(checkboxLabels[q]) {
checkboxLabels[q].className += " checkboxAreaCheckedLabel"
}
}
else {
checkboxArea.className = "checkboxArea";
}
checkboxArea.id = "myCheckbox" + q;
checkboxes[q].parentNode.insertBefore(checkboxArea, checkboxes[q]);
checkboxes[q]._ca = checkboxArea;
checkboxArea.onclick = new Function('rechangeCheckboxes('+q+')');
if (checkboxLabels[q]) {
checkboxLabels[q].onclick = new Function('changeCheckboxes('+q+')');
}
checkboxes[q].onkeydown = checkEvent;
}
return true;
}
//checking checkboxes
function checkCheckboxes(who, action) {
var what = checkboxes[who]._ca;
if(action == true) {
what.className = "checkboxAreaChecked";
what.checked = true;
}
if(action == false) {
what.className = "checkboxArea";
what.checked = false;
}
if(checkboxLabels[who]) {
if(checkboxes[who].checked) {
if(checkboxLabels[who].className.indexOf("checkboxAreaCheckedLabel") < 0) {
checkboxLabels[who].className += " checkboxAreaCheckedLabel";
}
} else {
checkboxLabels[who].className = checkboxLabels[who].className.replace("checkboxAreaCheckedLabel", "");
}
}
}
//changing checkboxes
function changeCheckboxes(who) {
setTimeout(function(){
if(checkboxes[who].checked) {
checkCheckboxes(who, true);
} else {
checkCheckboxes(who, false);
}
},10);
}
Please see the jquery stopImmediatePropagation() function here: http://docs.jquery.com/Types/Event#event.stopImmediatePropagation.28.29
I believe this will achieve what you are looking to do.
Edit: With more detail I may be able to provide a better answer.
Edit 2: It appears that there is no guarantee'd order of execution in Javascript, so inline code may not run before dynamically added code. In addition this particular function may only work if the other handlers are added using jQuery.
Edit 3:
A quick and dirty fix would be to add
<script type="text/javascript">var executeHandlers = false;</script>
to the top of the one html file.
Then edit the javascript file such that the event handlers have
if (executeHandlers !== false) { ... do the logic you normally would here ... }
as the body
This would add one line to the html file that needs to be treated differently, and should not impact the execution on the other pages.
Please note that this is a quick and dirty fix, and there are better ways to do this. Working with the constraints of an existing .js file, and only one file that needs to be treated differently, this seems to be the fastest / easiest way to the desired outcome, not necessarily the best.

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