why dosn't this onchange work - javascript

I am trying to work out a simple problem in js. I can't figure out why my speed method is not being called. I've inserted console.log() to check if every other method works and turns out it does. I've inserted code from html and js. It is a selection list, if i select a different value, speed method should be called, but it never does. Any help is appreciated.
(function() {
"use strict";
window.onload = function() {
document.getElementById("startbutton").onclick = displayWords;
document.getElementById("stopbutton").onclick = stop;
document.getElementById("speedMenu").onchange = speed;
};
var timer = null;
var speed = 171;
var count = 0;
function displayWords() {
console.log(" displayWords is called");
document.getElementById("stopbutton").disabled = false;
document.getElementById("startbutton").disabled = true;
document.getElementById("stopbutton").classList.remove("buttonBehaviour");
document.getElementById("startbutton").classList.add("buttonBehaviour");
document.getElementById("input").disabled = true;
timer = setInterval(display,speed,punctuation());
}
function stop() {
console.log(" stop is called");
document.getElementById("startbutton").disabled = false;
document.getElementById("stopbutton").disabled = true;
document.getElementById("stopbutton").classList.add("buttonBehaviour");
document.getElementById("startbutton").classList.remove("buttonBehaviour");
document.getElementById("display").innerHTML = "";
clearInterval(timer);
document.getElementById("input").disabled = false;
count = 0;
}
function speed() {
console.log(" speed is called");
var value = document.getElementById("speedMenu").options[document.getElementById("speedMenu")].value;
console.log(value);
clearInterval(timer);
var list = punctuation();
for(var i = 0; i < count ;i++) {
list.shift();
}
timer = setInterval(display,value,list);
}
function punctuation () {
console.log(" pun is called");
var words = document.getElementById("input").value.split(/[ \t\n]+/);
var list = [];
for (var i = 0; i < words.length; i++) {
var word = words[i];
var lastChar = word.charAt(word.length - 1);
if(lastChar === "," || lastChar === "." || lastChar === "!" || lastChar === "?" || lastChar === ";" || lastChar === ":") {
word = word.substring(0,word.length - 1);
list.push(word);
list.push(word);
} else {
list.push(word);
}
};
return list;
}
function display(words) {
count++;
console.log(" display is called");
document.getElementById("display").innerHTML = words.shift();
if(document.getElementById("med").checked) {
document.getElementById("display").style.fontSize = "36pt";
} else if(document.getElementById("big").checked) {
document.getElementById("display").style.fontSize = "48pt";
} else if(document.getElementById("bigger").checked) {
document.getElementById("display").style.fontSize = "60pt";
}
if( words.length == 0) {
clearInterval(timer);
}
}
}) ();
HTML code is following for the tag and method
<select id = "speedMenu">
<option value = "500">50 wpm</option>
<option value = "200">300 wpm</option>
<option value = "171" selected="selected">350 wpm</option>
<option value = "150">400 wpm</option>
<option value = "133">450 wpm</option>
<option value = "120">500 wpm</option>
</select>

You have a variable named speed and a function named speed. You have a name collision.
This is the minimal example of your code:
window.onload = function () {
console.log(speed);
};
var speed = 171;
function speed(){
}

Related

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++)

Other js function is ignoring my realtime calc function

I am at a lost here and have tried everything. My realtime calculation was being done into separate js file, but since I started using bootstrap template, it is not being executed. I have read through it and tried different thing but nothing is happening.
Php for calling realtime calc
<!-- ======================== PHONE INSURANCE ======================== -->
<select name="insurance" id='insurance' onChange="portInDatabase();">
<option disabled >Select Insurance</option>
<option value="None">None</option>
<option value="7">Yes</option>
</select><br>
<!-- ======================== PHONE CASE ======================== -->
<select name="case" id='case' onChange="portInDatabase()" onclick='portInDatabase()'>
<option disabled >Select Phone Case</option>
<option value="None">None</option>
<option value="25">Regular</option>
<option value="30">Wallet</option>
</select><br>
<!-- ======================== SCREEN PROTECTOR ======================== -->
<select name="screen" id='screen' onChange="portInDatabase();">
<option disabled >Select Screen Protector</option>
<option value="None">No</option>
<option value="15">Yes</option>
</select><br>
<!-- ======================== TOTAL FROM JS ======================== -->
<div id='total'></div>
Js for Real time calc(sorry for the long code)
// Array for plan prices
var plan_prices = new Array();
plan_prices["None"]= 0;
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
// Array for insurance where "None" is the id from the html and it is equivalent
// to value 0 and so on
var insurance_phone = new Array();
insurance_phone["None"]=0;
insurance_phone["7"]=7;
//Array for phone case for price calculation
var phone_case = new Array();
phone_case["None"]=0;
phone_case["25"] = 25;
phone_case["30"] = 30;
//Array for screen protector
var screen_protector = new Array();
screen_protector["None"]=0;
screen_protector["15"] = 15;
// function for getting the plan price from the dropList
function getPlanPrice() {
var planSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice3=selectForm.elements["plan"];
planSelected = plan_prices[selectedDevice3.value];
return planSelected;
}// end getPlanPrice
// function for getting the price when it is selected in the html dropList. This
// selection will single out the price we need for calculation.
function getInsurancePrice() {
var insuranceSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice4=selectForm.elements["insurance"];
insuranceSelected = insurance_phone[selectedDevice4.value];
return insuranceSelected;
}// end getInsurancePrice
// Get the price for the selected option in the dropList to calculate.
function getCasePrice() {
var caseSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice5=selectForm.elements["case"];
caseSelected = phone_case[selectedDevice5.value];
return caseSelected;
}// getCasePrice
// function to get the price for the screen.
function getScreenPrice() {
var screenSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice6=selectForm.elements["screen"];
screenSelected = screen_protector[selectedDevice6.value];
return screenSelected;
}// getScreenPrice
// This function splits the data in the database to calculate the price for the
// device when port in is selected or when upgrade is selected and then it also checks
// whether anything else is selected in the form and does the real time calculation and
// outputs the result.
function portInDatabase(){
console.log("PortInDatabase started..")
debugger;
var price1, price2, price3, price4, price5, price6 = 0;
var port = 0;
var newAct = 0;
var up = 0;
var down = 0;
var act= 25; //Activation fee
// if the selection is a number then execute this
if(!isNaN(getPlanPrice())){
price2= getPlanPrice();
}
if(!isNaN(getInsurancePrice())){
price3= getInsurancePrice();
}
if(!isNaN(getCasePrice())){
price4= getCasePrice();
}
if(!isNaN(getScreenPrice())){
price5= getScreenPrice();
}
// This if statement is executed when Port is selected in the dropList and then
// it splits the rows which is connected to the device accordingly and then checks
// whether any of the other dropLists are selected so it can then calulate them and output it.
debugger;
if (document.getElementById('myport').selected == true){
var selDev = document.getElementById('selectDevice').value;
var port = selDev.split('#')[4]; // number of row in the database
port= parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
port = port.toFixed(2); // rounds the decimal to 2
debugger;
document.getElementById('total').innerHTML= "Your Total: " +port;
}//end if
// for new Activation selection
else if(document.getElementById('srp').selected == true){
var selDev = document.getElementById('selectDevice').value;
var newAct = selDev.split('#')[1];
newAct= parseFloat(newAct) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
newAct = newAct.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +newAct;
}//elseif
//for upgrade selection
else if(document.getElementById('upgrade').selected == true){
var selDev = document.getElementById('selectDevice').value;
var up = selDev.split('#')[2];
up = parseFloat(up) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
up = up.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +up;
}//2nd elseif
//for down selection
else if(document.getElementById('down').selected == true){
var selDev= document.getElementById('selectDevice').value;
var down= selDev.split('#')[6];
down = parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
down = down.toFixed(2);
document.getElementsById('total').innerHTML= "Your Total: " +down;
}//end 3rd elseif
else{
return false;
}//end else
}// end portInDatabase
JS of styling that is preventing real time calc
var CuteSelect = CuteSelect || {};
FIRSTLOAD = true;
SOMETHINGOPEN = false;
CuteSelect.tools = {
canRun: function() {
var myNav = navigator.userAgent.toLowerCase();
var browser = (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
if(browser) {
return (browser > 8) ? true : false;
} else { return true; }
},
uniqid: function() {
var n= Math.floor(Math.random()*11);
var k = Math.floor(Math.random()* 1000000);
var m = String.fromCharCode(n)+k;
return m;
},
hideEverything: function() {
if(SOMETHINGOPEN) {
SOMETHINGOPEN = false;
targetThis = false;
var cells = document.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
var parent = cells[i].parentNode;
cells[i].style.opacity = '0';
cells[i].style.display = 'none';
}
}
}
},
getStyle: function() {
var css = '';
var stylesheets = document.styleSheets;
var css = '';
for(s = 0; s < stylesheets.length; s++) {
var classes = stylesheets[s].rules || stylesheets[s].cssRules;
for (var x = 0; x < classes.length; x++) {
if(classes[x].selectorText != undefined) {
var selectPosition = classes[x].selectorText.indexOf('select');
var optionPosition = classes[x].selectorText.indexOf('option');
var selectChar = classes[x].selectorText.charAt(selectPosition - 1);
var optionChar = classes[x].selectorText.charAt(optionPosition - 1);
if(selectPosition >= 0 && optionPosition >= 0 && (selectChar == '' || selectChar == '}' || selectChar == ' ') && (optionChar == '' || optionChar == '}' || optionChar == ' ')) {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]').replace(/\bselect\b/g, '[data-cuteselect-item]');
continue;
}
if(selectPosition >= 0) {
var character = classes[x].selectorText.charAt(selectPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\bselect\b/g, '[data-cuteselect-item]');
}
}
if(optionPosition >= 0) {
var character = classes[x].selectorText.charAt(optionPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]');
}
}
}
}
}
return css;
},
createSelect: function(item) {
// Create custom select
var node = document.createElement("div");
if(item.hasAttribute('id')) { // Catch ID
node.setAttribute('id', item.getAttribute('id'));
item.removeAttribute('id');
}
if(item.hasAttribute('class')) { // Catch Class
node.setAttribute('class', item.getAttribute('class'));
item.removeAttribute('class');
}
// Hide select
item.style.display = 'none';
// Get Default value (caption)
var caption = null;
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
caption = cells[0].innerHTML;
if(cells[i].hasAttribute('selected')) {
caption = cells[i].innerHTML;
break;
}
}
// Get select options
var options = '<div data-cuteselect-title>' + caption + '</div><div data-cuteselect-options><div data-cuteselect-options-container>';
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('disabled')) { continue; }
if(cells[i].hasAttribute('class')) { var optionStyle = ' class="' + cells[i].getAttribute('class') + '"'; } else { var optionStyle = ''; }
if(cells[i].hasAttribute('id')) { var optionId = ' id="' + cells[i].getAttribute('id') + '"'; } else { var optionId = ''; }
if(cells[i].hasAttribute('selected')) { options += '<div data-cuteselect-value="' + cells[i].value + '" data-cuteselect-selected="true"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
else { options += '<div data-cuteselect-value="' + cells[i].value + '"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
}
options += '</div></div>';
// New select customization
node.innerHTML = caption;
node.setAttribute('data-cuteselect-item', CuteSelect.tools.uniqid());
node.innerHTML = options; // Display options
item.setAttribute('data-cuteselect-target', node.getAttribute('data-cuteselect-item'));
item.parentNode.insertBefore(node, item.nextSibling);
// Hide all options
CuteSelect.tools.hideEverything();
},
//settings of the options, their position and all
show: function(item) {
if(item.parentNode.hasAttribute('data-cuteselect-item')) { var source = item.parentNode.getAttribute('data-cuteselect-item'); }
else { var source = item.getAttribute('data-cuteselect-item'); }
var cells = document.getElementsByTagName('select');
if(item.hasAttribute('data-cuteselect-title')) {
item = item.parentNode;
var cells = item.getElementsByTagName('div');
}
else { var cells = item.getElementsByTagName('div'); }
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
targetItem = cells[i];
cells[i].style.display = 'block';
setTimeout(function() { targetItem.style.opacity = '1'; }, 10);
cells[i].style.position = 'absolute';
cells[i].style.left = item.offsetLeft + 'px';
cells[i].style.top = (item.offsetTop + item.offsetHeight) + 'px';
}
}
item.focus();
SOMETHINGOPEN = item.getAttribute('data-cuteselect-item');
},
selectOption: function(item) {
var label = item.innerHTML;
var value = item.getAttribute('data-cuteselect-value');
var parent = item.parentNode.parentNode.parentNode;
var target = parent.getAttribute('data-cuteselect-item');
var cells = parent.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-title')) { cells[i].innerHTML = label; }
}
// Real select
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) {
var source = cells[i].getAttribute('data-cuteselect-target');
if(source == target) { cells[i].value = value; }
}
//CuteSelect.tools.hideEverything();
},
writeStyles: function() {
toWrite = '<style type="text/css">' + CuteSelect.tools.getStyle() + ' [data-cuteselect-options] { opacity: 0; display: none; }</style>';
document.write(toWrite);
}
};
CuteSelect.event = {
parse: function() {
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) { CuteSelect.tools.createSelect(cells[i]); }
},
listen: function() {
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) { CuteSelect.tools.hideEverything(); }
};
document.onclick = function(event) {
FIRSTLOAD = false;
if((!event.target.getAttribute('data-cuteselect-item') && !event.target.getAttribute('data-cuteselect-value') && !event.target.hasAttribute('data-cuteselect-title')) || ((event.target.hasAttribute('data-cuteselect-item') || event.target.hasAttribute('data-cuteselect-title')) && SOMETHINGOPEN)) {
CuteSelect.tools.hideEverything();
return;
}
//when selected the option dropdown list closes
var action = event.target;
if(event.target.getAttribute('data-cuteselect-value')) {
CuteSelect.tools.selectOption(action);
CuteSelect.tools.hideEverything();
}
else { CuteSelect.tools.show(action); }
return false;
}
},
manage: function() {
if(CuteSelect.tools.canRun()) { // IE Compatibility
CuteSelect.event.parse();
CuteSelect.event.listen();
CuteSelect.tools.writeStyles();
}
}
};
// document.onload(function() {
CuteSelect.event.manage();
// });
I did not want to post this long question, but I am lost and do not know what to do. Thanks and sorry.

Javascript: scope effect despite order of execution

Please note: This is not a question about scope, per se. I understand that in order to make the code work, I should make a deep copy of the variable board rather than assigning var tboard = board. However, I am not clear why making a shallow copy has the effect I describe below.
I am experiencing something I find baffling. Basically, a global variable (board) gets altered and I have no clue how. board is initialized in the function NewGame() (which is called from select()) as an empty array. After it is initialized, nothing else is called until the user clicks a square on the board (assuming the user has selected Xs for simplicity). When that happens, the function playerMove() is called. The baffling thing is that console.log(board) at the top of playerMove() prints out an array that has an x is the clicked position and os everywhere else (ie not empty). This is bizarre because the board is empty at the end of select() (which called NewGame()) and nothing else should happen in between. To demonstrate this, I print out the function name at the top of each function and I print out the board variable in the select() function and playerMove() function to show that it changes despite nothing else being called. Please note that to get this behavior, refresh the page (otherwise the board variable starts out full of os). I think this must be somewhat an issue of scope (because I am not making a deep copy of board) but it's strange because I have no clue what is being called that is changing the variable before it gets printed out at the top of playerMove().
Here is the link to my pen and the code: http://codepen.io/joshlevy89/pen/MKjxop?editors=101
$(document).ready(function() {
var pSym; // player's symbol
var cSym; // computer's symbol
var board;
var whosMove; // can be "player" or "computer" or "neither"
var gameOver;
setup();
$("#newgame").on('click', '#X', select);
$("#newgame").on('click', '#O', select);
$("#restart").on('click', setup);
$("table").on('click', 'td', playerMove);
function playerMove()
{
console.log('playerMove');
console.log(board);
if (whosMove === "player")
{
var val = $(this).data('value');
$('#g' + val).text(pSym);
var arr = PositionToCoords(val);
board[arr[0]][arr[1]] = pSym;
var tboard = board;
var gc = gameCheck(tboard);
if (gc>=0)
{
endGame(gc);
setTimeout(function(){setup();}, 1000);
return;
}
whosMove = "computer";
computerMove();
}
}
function computerMove() {
console.log('computerMove');
//var p1 = Math.floor(Math.random() * 3);
//var p2 = Math.floor(Math.random() * 3);
var tboard = board;
var pos = chooseMove(tboard);
var arr = PositionToCoords(pos);
board[arr[0]][arr[1]] = cSym;
DrawPosition(arr[0], arr[1], cSym);
var tboard = board;
var gc = gameCheck(tboard);
if (gc>=0) {
endGame(gc);
setTimeout(function(){setup();}, 1000);
return;
}
whosMove = "player";
}
function chooseMove(inboard) {
console.log('chooseMove');
// get the possible moves
var moves=[];
var scores = [];
for (var i=1;i<10;i++) {
var arr = PositionToCoords(i);
if (inboard[arr[0]][arr[1]] === undefined) {
moves.push(i);
var tboard = inboard;
tboard[arr[0]][arr[1]] = cSym;
var gc = gameCheck(tboard);
scores.push(gc);
}
}
//console.log(moves);
//console.log(scores);
return moves[0]; // TEMPORARY
}
function endGame(gc) {
console.log('endGame');
var str;
if (gc===1) { // somebody won
if (whosMove==="player"){
str = "You Won!"
}
else {
str = "You Lost :(";
}
}
else if (gc === 0){//draw
str = "It's a draw."
}
html = '<div id="closer">' + str + '</div>';
$('#endgame').html(html);
}
function gameCheck(tboard) {
console.log('gameCheck');
// get symbol to check for
var sym;
if (whosMove === "player") {
sym = pSym;
} else {
sym = cSym;
}
// check if in a row
var hrow;
var vrow;
// check for horizonal row
for (var i = 0; i < 3; i++) {
hrow = true;
vrow = true;
for (var j = 0; j < 3; j++) {
if (tboard[i][j] !== sym) {
hrow = false;
}
if (tboard[j][i] !== sym) {
vrow = false;
}
}
if ((hrow) || (vrow)) {
return 1;
}
}
var fdrow = true;
var bdrow = true;
for (var i = 0; i < 3; i++) {
if (tboard[i][i] !== sym) {
fdrow = false;
}
if (tboard[i][2 - i] !== sym) {
bdrow = false;
}
}
if ((fdrow) || (bdrow)) {
return 1;
}
// otherwise, check if board is full
var full = true;
for (var i = 1; i < 10; i++) {
var arr = PositionToCoords(i);
if (tboard[arr[0]][arr[1]] === undefined) {
full = false;
break;
}
}
if (full === true) {
return 0;
}
// if neither 0 (tie) or win (1), return -1 (game not over)
return -1;
}
function select() {
console.log('select');
pSym = $(this).data('value');
$('#newgame').html('');
NewGame();
console.log(board);
}
function setup() {
console.log('select');
$('#endgame').html('');
html = '<div id="opener">Xs or Os? <div id="buttons">';
html += '<div id="X" data-value="X" class="btn btn-default">Xs</div>';
html += '<div id="O" data-value="O" class="btn btn-default">Os</div>';
html += '</div></div>';
$('#newgame').html(html);
}
function NewGame() {
console.log('NewGame');
$('td').empty();
board = new Array(3);
for (i = 0; i < 3; i++) {
board[i] = new Array(3)
};
if (pSym === "X") {
cSym = "O";
whosMove = "player";
} else {
cSym = "X";
whosMove = "computer";
computerMove();
}
}
function DrawPosition(p1, p2, sym) {
console.log('DrawPosition');
var pos = p1 * 3 + (p2 + 1);
$("#g" + pos).text(sym)
}
function PositionToCoords(pos) {
console.log('PositionToCoords');
var p1 = Math.ceil(pos / 3) - 1;
var p2 = ((pos - 1) % 3);
var arr = [p1, p2];
return arr;
}
});
Thanks in advance.
Simply add the break in the for loop fixes the problem. Am I missing anything?
function chooseMove(inboard) {
console.log('chooseMove');
// get the possible moves
var moves = [];
var scores = [];
for (var i = 1; i < 10; i++) {
var arr = PositionToCoords(i);
if (inboard[arr[0]][arr[1]] === undefined) {
moves.push(i);
var tboard = inboard;
tboard[arr[0]][arr[1]] = cSym;
var gc = gameCheck(tboard);
scores.push(gc);
break; // <<<<<<<<<<<< This break guarantees that the computer only makes one move
}
}
//console.log(moves);
//console.log(scores);
return moves[0]; // TEMPORARY
}

SSRS Report Manager javascript fails in non-IE browsers for Drop Down Menus

I've been debugging the ReportingServices.js file using Firefox and Firebug. I've found that the reason SSRS (SQL Server Reporting Services) Report Manager (web front end for Reports) doesn't work in Firefox (v7.0.1) is that it's using javascript .lastChild to find elements. Unfortunately, Firefox also picks up on whitespace as TextNode elements causing the element selection to not work as expected.
This works in IE and hopefully someone knows a solution to this. I edited the javascript to get round one bug but then hit another more complicated one so probably a mine field to try to fix manually. Hopefully there is some update or patch available.
This is running SQL Server 2008 R2 Standard edition on a Windows 2008 R2 Datacenter server.
Apologies if you feel this is not the forum for such a question. In that case, please suggest where else I should ask the question if it's not appropriate. It is kindof a javascript problem but likely with a software update solution.
Updated:
After a few hours of fixing the browser compatibility bugs in the ReportingServices.js file I managed to get it to work on Firefox, Chrome, Opera and Safari as well as IE. Sorry that my answer below is in 2 parts; I posted the entire code of the updated ReportingServices.js for the solution.
After a few hours hacking around with the original ReportingServices.js file I managed to fix the javascript to work on Firefox, Chrome, Opera and Safari as well as IE.
Even though it's a bit big I've posted the whole edited ReportingServices.js below for others to use if needed. I've put "chris edit" comments showing the old lines above their edits so you can (if you care) follow what I've changed. I've also summarized these changes at the top of the code.
The SSRS report manager web interface is very useful and it would be a shame not to use it just because Microsoft didn't bother to test it on other browsers than IE. This is why I always prefer jQuery over plain javascript to avoid these kind of cross browser compatibility issues.
I had to post it in 2 parts. Hope this helps others!
/*
Author: Chris Snowden
Modified Date: 21st October 2011
ReportingServices.js file for SQL Server 2008 R2 Reporting Services
Updated to fix a bug whereby drop down context menus didn't work
for any other browser than IE.
1) I added functions to find firstChild and lastChild while skipping any
whitespace TextNode elements.
2) I updated the Clicked function to get at the table element value in a way
that works for firefox.
3) I updated the SplitContextMenuConfigString function to access the table
cells by first looping through each row and then the cells.
Drop downs now work on Firefox, Chrome, Opera and Safari as well as IE.
*/
var checkBoxCount;
var checkBoxId;
var checkBoxHead;
// Context menu
var _divContextMenu; // The container for the context menu
var _selectedIdHiddenField; // The id of the item that opened th context menu
var _timeOutLimit = 3000; // How long the context menu stays for after the cursor in no longer over it
var _timeOutTimer; // The timout for the context menu
var _itemSelected = false;
var _mouseOverContext = false; // If the mouse is over the context menu
var _contextMenusIds; // The array of the diffrent context menus
var _fadeTimeouts; // The array of timouts used for the fade effect
var _onLink = false; // If the user is over a name link
var _selectedItemId;
var _tabFocusedItem = '';
var _mouseOverItem = '';
var _unselectedItemStyle;
var _currentContextMenuId; // ID of currently displayed context menu
var _currentMenuItemId = null; // ID of currently selected context menu item
// Search bar
var _searchTextBoxID;
var _defaultSearchValue; // The value that the box defaults to.
// start chris edit
// new functions to find firstChild and lastChild but skipping whitespace elements
function firstChildNoWS(element) {
var child = element.firstChild;
while (child != null && child.isElementContentWhitespace) {
child = child.nextSibling;
}
return child;
}
function lastChildNoWS(element) {
var child = element.lastChild;
while (child != null && child.isElementContentWhitespace) {
child = child.previousSibling;
}
return child;
}
// end chris edit
function ToggleItem(itemId) {
var item = document.getElementById(itemId);
if (item.style.display == 'none')
item.style.display = 'inline';
else
item.style.display = 'none';
}
function ToggleButtonImage(image1ID, image2ID) {
var image1 = document.getElementById(image1ID);
var image2 = document.getElementById(image2ID);
if (image1.style.display == 'none') {
image1.style.display = 'inline-block';
image2.style.display = 'none';
}
else {
image1.style.display = 'none';
image2.style.display = 'inline-block';
}
}
function SetFocus(id) {
var obj = document.getElementById(id);
if (obj != null && !obj.disabled)
obj.focus();
}
// Validates that an extension has been selected
function ValidateDropDownSelection(source, args) {
var obj = document.getElementById(source.controltovalidate);
if (obj.options[0].selected && !obj.disabled)
args.IsValid = false;
else
args.IsValid = true;
}
/// selectAll
/// selects all the checkBoxes with the given id
function selectAll() {
var i;
var id;
var checked = checkBoxHead.checked;
for (i = 0; i < checkBoxCount; i++) {
id = checkBoxId + i;
document.getElementById(id).checked = checked;
}
}
/// onSglCheck
/// performs actions when a single checkBox is checked or unchecked
/// cb -> the checkBox generating the event
/// topId -> id of the "select all" checkBox
function onSglCheck() {
// uncheck the top checkBox
checkBoxHead.checked = false;
}
/// ToggleButton
/// Toggle a buttons enable state
function ToggleButton(id, disabled) {
if (document.getElementById(id) != null)
document.getElementById(id).disabled = disabled;
}
function ToggleValidator(id, enabled) {
document.getElementById(id).enabled = enabled;
}
function SetCbVars(cbid, count, cbh) {
checkBoxCount = count;
checkBoxId = cbid;
checkBoxHead = cbh;
}
/// Check to see if any check boxes should disable
/// a control
/// cbid -> id prefix of the checkBoxes
/// cbCount -> total checkBoxes to check
/// hidden -> input to look for
/// display -> control to disable
function CheckCheckBoxes(cbid, hidden, display) {
var i;
var id;
var disable;
disable = false;
for (i = 0; i < checkBoxCount; i++) {
id = cbid + i;
if (document.getElementById(id).checked) {
id = hidden + id;
if (document.getElementById(id) != null) {
disable = true;
break;
}
}
}
ToggleButton(display, disable);
}
function HiddenCheckClickHandler(hiddenID, promptID, promptStringID) {
var hiddenChk = document.getElementById(hiddenID);
var promptChk = document.getElementById(promptID);
// prompt should be in opposite state of hidden
promptChk.checked = !hiddenChk.checked;
}
function validateSaveRole(source, args) {
var i;
var id;
var c = 0;
for (i = 0; i < checkBoxCount; i++) {
id = checkBoxId + i;
if (document.getElementById(id).checked) c++;
}
if (0 == c)
args.IsValid = false;
else
args.IsValid = true;
}
/// Pad an integer less then 10 with a leading zero
function PadIntWithZero(val) {
var s = val.toString();
if (val < 10 && val >= 0) {
if (s.length == 1)
s = "0" + s;
else if (s.length > 2)
s = s.substring(s.length - 2, s.length);
}
return s;
}
/// Pad the contents of an input with leading zeros if necesarry
function PadInputInteger(id) {
document.getElementById(id).value = PadIntWithZero(document.getElementById(id).value);
}
/// text of confirmation popup when a single item is selected for deletion
/// e.g. "Are you sure you want to delete this item"
var confirmSingle;
/// text of confirmation popup when multiple items are selected for deletion
/// e.g. "Are you sure you want to delete these items"
var confirmMultiple;
function SetDeleteTxt(single, multiple) {
confirmSingle = single;
confirmMultiple = multiple;
}
/// doCmDel: DoConfirmDelete
/// Given a number of checked items, confirm their deletion
/// return true if OK was clicked; false otherwise
function doCmDel(checkedCount) {
var confirmTxt = confirmSingle;
if (checkedCount == 0)
return false;
if (checkedCount > 1)
confirmTxt = confirmMultiple;
return confirm(confirmTxt);
}
/// on non-Netscape browsers, confirm deletion of 0 or more items
function confirmDelete() {
return doCmDel(getChkCount());
}
/// confirm deletion of policies
function confirmDeletePlcies(alertString) {
var count = getChkCount();
if (count >= checkBoxCount) {
alert(alertString);
return false;
}
return doCmDel(count);
}
/// counts whether 0, 1, or more than 1 checkboxes are checked
/// returns 0, 1, or 2
function getChkCount() {
var checkedCount = 0;
for (i = 0; i < checkBoxCount && checkedCount < 2; i++) {
if (document.getElementById(checkBoxId + i).checked) {
checkedCount++;
}
}
return checkedCount;
}
function ToggleButtonBasedOnCheckBox(checkBoxId, toggleId, reverse) {
var chkb = document.getElementById(checkBoxId);
if (chkb != null) {
if (chkb.checked == true)
ToggleButton(toggleId, reverse); // enable if reverse == false
else
ToggleButton(toggleId, !reverse); // disable if reverse == false
}
}
function ToggleButtonBasedOnCheckBoxWithOverride(checkBoxId, toggleId, overrideToDisabled, reverse) {
if (overrideToDisabled == true)
ToggleButton(toggleId, true); // disable
else
ToggleButtonBasedOnCheckBox(checkBoxId, toggleId, reverse);
}
function ToggleButtonBasedOnCheckBoxes(checkBoxId, checkboxId2, toggleId) {
var chkb = document.getElementById(checkBoxId);
if (chkb != null) {
if (chkb.checked == true)
ToggleButtonBasedOnCheckBox(checkboxId2, toggleId, false);
else
ToggleButton(toggleId, true); // disable
}
}
function ToggleButtonBasedOnCheckBoxesWithOverride(checkBoxId, checkboxId2, toggleId, overrideToDisabled) {
if (overrideToDisabled == true)
ToggleButton(toggleId, true); // disable
else
ToggleButtonBasedOnCheckBoxes(checkBoxId, checkboxId2, toggleId);
}
function ToggleValidatorBasedOnCheckBoxWithOverride(checkBoxId, toggleId, overrideToDisabled, reverse) {
if (overrideToDisabled == true)
ToggleValidator(toggleId, false);
else {
var chkb = document.getElementById(checkBoxId);
if (chkb != null) {
ToggleValidator(toggleId, chkb.checked != reverse);
}
}
}
function ToggleValidatorBasedOnCheckBoxesWithOverride(checkBoxId, checkBoxId2, toggleId, overrideToDisabled, reverse) {
if (overrideToDisabled == true)
ToggleValidator(toggleId, false);
else {
var chkb = document.getElementById(checkBoxId);
if (chkb != null) {
if (chkb.checked == reverse)
ToggleValidator(toggleId, false);
else
ToggleValidatorBasedOnCheckBoxWithOverride(checkBoxId2, toggleId, overrideToDisabled, reverse);
}
}
}
function CheckButton(buttonID, shouldCheck) {
document.getElementById(buttonID).checked = shouldCheck;
}
function EnableMultiButtons(prefix) {
// If there are no multibuttons, there is no reason to iterate the
// list of checkboxes.
if (checkBoxCount == 0 || multiButtonList.length == 0)
return;
var enableMultiButtons = false;
var multipleCheckboxesSelected = false;
// If the top level check box is checked, we know the state of all
// of the checkboxes
var headerCheckBox = document.getElementById(prefix + "ch");
if (headerCheckBox != null && headerCheckBox.checked) {
enableMultiButtons = true;
multipleCheckboxesSelected = checkBoxCount > 1;
}
else {
// Look at each checkbox. If any one of them is checked,
// enable the multi buttons.
var foundOneChecked = false;
var i;
for (i = 0; i < checkBoxCount; i++) {
var checkBox = document.getElementById(prefix + 'cb' + i);
if (checkBox.checked) {
if (foundOneChecked) {
multipleCheckboxesSelected = true;
break;
}
else {
enableMultiButtons = true;
foundOneChecked = true;
}
}
}
}
// Enable/disable each of the multi buttons
var j;
for (j = 0; j < multiButtonList.length; j++) {
var button = document.getElementById(multiButtonList[j]);
if (button.allowMultiSelect)
button.disabled = !enableMultiButtons;
else
button.disabled = !enableMultiButtons || multipleCheckboxesSelected;
}
}
//function ShadowCopyPassword(suffix)
function MarkPasswordFieldChanged(suffix) {
if (event.propertyName == "value") {
var pwdField = document.getElementById("ui_txtStoredPwd" + suffix);
//var shadowField = document.getElementById("ui_shadowPassword" + suffix);
var shadowChanged = document.getElementById("ui_shadowPasswordChanged" + suffix);
// Don't shadow copy during initialization
if (pwdField.IsInit) {
//shadowField.value = pwdField.value;
//pwdField.UserEnteredPassword = "true";
shadowChanged.value = "true";
// Update validator state (there is no validator on the data driven subscription page)
var validator = document.getElementById("ui_validatorPassword" + suffix)
if (validator != null)
ValidatorValidate(validator);
}
}
}
function InitDataSourcePassword(suffix) {
var pwdField = document.getElementById("ui_txtStoredPwd" + suffix);
var shadowChanged = document.getElementById("ui_shadowPasswordChanged" + suffix);
// var shadowField = document.getElementById("ui_shadowPassword" + suffix);
var storedRadioButton = document.getElementById("ui_rdoStored" + suffix);
var pwdValidator = document.getElementById("ui_validatorPassword" + suffix);
pwdField.IsInit = false;
// Initialize the field to the shadow value (for when the user clicks back/forward)
// Or to a junk initial value.
if (pwdValidator != null && storedRadioButton.checked) {
/* if (shadowField.value.length > 0)
pwdField.value = shadowField.value;
else*/
pwdField.value = "********";
}
else
shadowChanged.value = "true"; // shadowChanged will be ignored if the page is submitted without storedRadioButton.checked
// Now that the initial value is set, track changes to the password field
pwdField.IsInit = true;
// There is no validator on the data driven subscription page (no stored radio button either)
if (pwdValidator != null)
ValidatorValidate(pwdValidator);
}
function SetNeedPassword(suffix) {
// Set a flag indicating that we need the password
var pwdField = document.getElementById("ui_txtStoredPwd" + suffix);
pwdField.NeedPassword = "true";
// Make the validator visible
ValidatorValidate(document.getElementById("ui_validatorPassword" + suffix));
}
function UpdateValidator(src, validatorID) {
if (src.checked) {
var validator = document.getElementById(validatorID);
ValidatorValidate(validator);
}
}
function ReEnterPasswordValidation(source, arguments) // source = validator
{
var validatorIdPrefix = "ui_validatorPassword"
var suffix = source.id.substr(validatorIdPrefix.length, source.id.length - validatorIdPrefix.length);
var storedRadioButton = document.getElementById("ui_rdoStored" + suffix);
var pwdField = document.getElementById("ui_txtStoredPwd" + suffix);
var shadowChanged = document.getElementById("ui_shadowPasswordChanged" + suffix);
var customDataSourceRadioButton = document.getElementById("ui_rdoCustomDataSource" + suffix);
var isCustomSelected = true;
if (customDataSourceRadioButton != null)
isCustomSelected = customDataSourceRadioButton.checked;
if (!isCustomSelected || // If the custom (vs shared) data source radio button exists and is not selected, we don't need the pwd.
storedRadioButton.checked == false || // If the data source is not using stored credentials, we don't need the password
pwdField.UserEnteredPassword == "true" || // If the password has changed, we don't need to get it from the user
pwdField.NeedPassword != "true" || // If no credentials have changed, we don't need the password
shadowChanged.value == "true") // If the user has typed a password
arguments.IsValid = true;
else
arguments.IsValid = false;
}
function ValidateDataSourceSelected(source, arguments) {
var validatorIdPrefix = "ui_sharedDSSelectedValidator"
var suffix = source.id.substr(validatorIdPrefix.length, source.id.length - validatorIdPrefix.length);
var sharedRadioButton = document.getElementById("ui_rdoSharedDataSource" + suffix);
var hiddenField = document.getElementById("ui_hiddenSharedDS" + suffix);
arguments.IsValid = (sharedRadioButton != null && !sharedRadioButton.checked) || hiddenField.value != "NotSelected";
}
/**************************************************************************/
// MultiValueParamClass
function MultiValueParamClass(thisID, visibleTextBoxID, floatingEditorID, floatingIFrameID, paramObject,
hasValidValues, allowBlank, doPostbackOnHide, postbackScript) {
this.m_thisID = thisID;
this.m_visibleTextBoxID = visibleTextBoxID;
this.m_floatingEditorID = floatingEditorID;
this.m_floatingIFrameID = floatingIFrameID;
this.m_paramObject = paramObject;
this.m_hasValidValues = hasValidValues;
this.m_allowBlank = allowBlank;
this.m_doPostbackOnHide = doPostbackOnHide;
this.m_postbackScript = postbackScript;
this.UpdateSummaryString();
}
function ToggleVisibility() {
var floatingEditor = GetControl(this.m_floatingEditorID);
if (floatingEditor.style.display != "inline")
this.Show();
else
this.Hide();
}
MultiValueParamClass.prototype.ToggleVisibility = ToggleVisibility;
function Show() {
var floatingEditor = GetControl(this.m_floatingEditorID);
if (floatingEditor.style.display == "inline")
return;
// Set the correct size of the floating editor - no more than
// 150 pixels high and no less than the width of the text box
var visibleTextBox = GetControl(this.m_visibleTextBoxID);
if (this.m_hasValidValues) {
if (floatingEditor.offsetHeight > 150)
floatingEditor.style.height = 150;
floatingEditor.style.width = visibleTextBox.offsetWidth;
}
var newEditorPosition = this.GetNewFloatingEditorPosition();
floatingEditor.style.left = newEditorPosition.Left;
floatingEditor.style.top = newEditorPosition.Top;
floatingEditor.style.display = "inline";
var floatingIFrame = GetControl(this.m_floatingIFrameID);
floatingIFrame.style.left = floatingEditor.style.left;
floatingIFrame.style.top = floatingEditor.style.top;
floatingIFrame.style.width = floatingEditor.offsetWidth;
floatingIFrame.style.height = floatingEditor.offsetHeight;
floatingIFrame.style.display = "inline";
// If another multi value is open, close it first
if (this.m_paramObject.ActiveMultValue != this && this.m_paramObject.ActiveMultiValue != null)
ControlClicked(this.m_paramObject.id);
this.m_paramObject.ActiveMultiValue = this;
if (floatingEditor.childNodes[0].focus) floatingEditor.childNodes[0].focus();
this.StartPolling();
}
MultiValueParamClass.prototype.Show = Show;
function Hide() {
var floatingEditor = GetControl(this.m_floatingEditorID);
var floatingIFrame = GetControl(this.m_floatingIFrameID);
// Hide the editor
floatingEditor.style.display = "none";
floatingIFrame.style.display = "none";
this.UpdateSummaryString();
if (this.m_doPostbackOnHide)
eval(this.m_postbackScript);
// Check that the reference is still us in case event ordering
// caused another multivalue to click open
if (this.m_paramObject.ActiveMultiValue == this)
this.m_paramObject.ActiveMultiValue = null;
}
MultiValueParamClass.prototype.Hide = Hide;
function GetNewFloatingEditorPosition() {
// Make the editor visible
var visibleTextBox = GetControl(this.m_visibleTextBoxID);
var textBoxPosition = GetObjectPosition(visibleTextBox);
return { Left: textBoxPosition.Left, Top: textBoxPosition.Top + visibleTextBox.offsetHeight };
}
MultiValueParamClass.prototype.GetNewFloatingEditorPosition = GetNewFloatingEditorPosition;
function UpdateSummaryString() {
var summaryString;
if (this.m_hasValidValues)
summaryString = GetValueStringFromValidValueList(this.m_floatingEditorID);
else
summaryString = GetValueStringFromTextEditor(this.m_floatingEditorID, false, this.m_allowBlank);
var visibleTextBox = GetControl(this.m_visibleTextBoxID);
visibleTextBox.value = summaryString;
}
MultiValueParamClass.prototype.UpdateSummaryString = UpdateSummaryString;
function StartPolling() {
setTimeout(this.m_thisID + ".PollingCallback();", 100);
}
MultiValueParamClass.prototype.StartPolling = StartPolling;
function PollingCallback() {
// If the editor isn't visible, no more events.
var floatingEditor = GetControl(this.m_floatingEditorID);
if (floatingEditor.style.display != "inline")
return;
// If the text box moved, something on the page resized, so close the editor
var expectedEditorPos = this.GetNewFloatingEditorPosition();
if (floatingEditor.style.left != expectedEditorPos.Left + "px" ||
floatingEditor.style.top != expectedEditorPos.Top + "px") {
this.Hide();
}
else {
this.StartPolling();
}
}
MultiValueParamClass.prototype.PollingCallback = PollingCallback;
/*****************************************************************************/
function GetObjectPosition(obj) {
var totalTop = 0;
var totalLeft = 0;
while (obj != document.body) {
// Add up the position
totalTop += obj.offsetTop;
totalLeft += obj.offsetLeft;
// Prepare for next iteration
obj = obj.offsetParent;
}
totalTop += obj.offsetTop;
totalLeft += obj.offsetLeft;
return { Left: totalLeft, Top: totalTop };
}
function GetValueStringFromTextEditor(floatingEditorID, asRaw, allowBlank) {
var span = GetControl(floatingEditorID);
var editor = span.childNodes[0];
var valueString = editor.value;
// Remove the blanks
if (!allowBlank) {
// Break down the text box string to the individual lines
var valueArray = valueString.split("\r\n");
var delimiter;
if (asRaw)
delimiter = "\r\n";
else
delimiter = ", ";
var finalValue = "";
for (var i = 0; i < valueArray.length; i++) {
// If the string is non-blank, add it
if (valueArray[i].length > 0) {
if (finalValue.length > 0)
finalValue += delimiter;
finalValue += valueArray[i];
}
}
return finalValue;
}
else {
if (asRaw)
return valueString;
else
return valueString.replace(/\r\n/g, ", ");
}
}
function GetValueStringFromValidValueList(editorID) {
var valueString = "";
// Get the table
var div = GetControl(editorID);
var table = div.childNodes[0];
if (table.nodeName != "TABLE") // Skip whitespace if needed
table = div.childNodes[1];
// If there is only one element, it is a real value, not the select all option
var startIndex = 0;
if (table.rows.length > 1)
startIndex = 1;
for (var i = startIndex; i < table.rows.length; i++)
{
// Get the first cell of the row
var firstCell = table.rows[i].cells[0];
var span = firstCell.childNodes[0];
var checkBox = span.childNodes[0];
var label = span.childNodes[1];
if (checkBox.checked) {
if (valueString.length > 0)
valueString += ", ";
// chris edit - valueString += label.firstChild.nodeValue;
valueString += firstChildNoWS(label).nodeValue;
}
}
return valueString;
}
function MultiValidValuesSelectAll(src, editorID)
{
// Get the table
var div = GetControl(editorID);
var table = div.childNodes[0];
if (table.nodeName != "TABLE")
table = div.childNodes[1];
for (var i = 1; i < table.rows.length; i++)
{
// Get the first cell of the row
var firstCell = table.rows[i].cells[0];
var span = firstCell.childNodes[0];
var checkBox = span.childNodes[0];
checkBox.checked = src.checked;
}
}
function ValidateMultiValidValue(editorID, errMsg)
{
var summaryString = GetValueStringFromValidValueList(editorID);
var isValid = summaryString.length > 0;
if (!isValid)
alert(errMsg)
return isValid;
}
function ValidateMultiEditValue(editorID, errMsg) {
// Need to check for a value specified. This code only runs if not allow blank.
// GetValueStringFromTextEditor filters out blank strings. So if it was all blank,
// the final string will be length 0
var summaryString = GetValueStringFromTextEditor(editorID, true, false)
var isValid = false;
if (summaryString.length > 0)
isValid = true;
if (!isValid)
alert(errMsg);
return isValid;
}
function GetControl(controlID) {
var control = document.getElementById(controlID);
if (control == null)
alert("Unable to locate control: " + controlID);
return control;
}
function ControlClicked(formID) {
var form = GetControl(formID);
if (form.ActiveMultiValue != null)
form.ActiveMultiValue.Hide();
}
Part 2 of updated ReportingServices.js from my answer:
// --- Context Menu ---
// This function is called in the onload event of the body.
// It hooks the context menus up to the Javascript code.
// divContextMenuId, is the id of the div that contains the context menus
// selectedIdHiddenFieldId, is the id of the field used to post back the name of the item clicked
// contextMenusIds, is an array of the ids of the context menus
// searchTextBox ID, is the id of the search box
// defaultSearchValue. the value the search box has by default
function InitContextMenu(divContextMenuId, selectedIdHiddenFieldId, contextMenusIds, searchTextBoxID, defaultSearchValue ) {
ResetSearchBar( searchTextBoxID, defaultSearchValue );
_divContextMenu = document.getElementById(divContextMenuId);
_selectedIdHiddenField = document.getElementById(selectedIdHiddenFieldId);
_contextMenusIds = contextMenusIds;
_divContextMenu.onmouseover = function() { _mouseOverContext = true; };
_divContextMenu.onmouseout = function() {
if (_mouseOverContext == true) {
_mouseOverContext = false;
if (_timeOutTimer == null) {
_timeOutTimer = setTimeout(TimeOutAction, _timeOutLimit);
}
}
};
document.body.onmousedown = ContextMouseDown;
AddKeyDownListener();
}
// This handler stops bubling when arrow keys Up or Down pressed to prevent scrolling window
function KeyDownHandler(e)
{
// Cancel window scrolling only when menu is opened
if(_currentContextMenuId == null)
{
return true;
}
if(!e)
{
e = window.event;
}
var key = e.keyCode;
if(key == 38 || key == 40)
{
return false;
}
else
{
return true;
}
}
function AddKeyDownListener()
{
if(document.addEventListener)
{
document.addEventListener('keydown', KeyDownHandler, false);
}
else
{
document.onkeydown = KeyDownHandler;
}
}
// This function starts the context menu timeout process
function TimeOutAction() {
if (_mouseOverContext == false) {
UnSelectedMenuItem()
}
_timeOutTimer = null;
}
// This function is called when a name tag is clicked, it displays the contextmenu for a given item.
function Clicked(event, contextMenuId) {
if (!_onLink) {
ClearTimeouts();
SelectContextMenuFromColletion(contextMenuId);
_itemSelected = true;
// **Cross browser compatibility code**
// Some browsers will not pass the event so we need to get it from the window instead.
if (event == null)
event = window.event;
var selectedElement = event.target != null ? event.target : event.srcElement;
var outerTableElement = GetOuterElementOfType(selectedElement, 'table');
var elementPosition = GetElementPosition(outerTableElement);
_selectedItemId = outerTableElement.id;
// chris edit - _selectedIdHiddenField.value = outerTableElement.value;
_selectedIdHiddenField.value = outerTableElement.attributes["value"].value;
outerTableElement.className = "msrs-SelectedItem";
ResetContextMenu();
var contextMenuHeight = _divContextMenu.offsetHeight;
var contextMenuWidth = _divContextMenu.offsetWidth;
var boxHeight = outerTableElement.offsetHeight;
var boxWidth = outerTableElement.offsetWidth;
var boxXcoordinate = elementPosition.left;
var boxYcooridnate = elementPosition.top;
var pageWidth = 0, pageHeight = 0;
// **Cross browser compatibility code**
if (typeof (window.innerWidth) == 'number') {
//Non-IE
pageWidth = window.innerWidth;
pageHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
//IE 4 compatible
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
// **Cross browser compatibility code**
var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
var pageXOffSet = document.all ? iebody.scrollLeft : pageXOffset
var pageYOffSet = document.all ? iebody.scrollTop : pageYOffset
_divContextMenu.style.left = SetContextMenuHorizonatalPosition(pageWidth, pageXOffSet, boxXcoordinate, contextMenuWidth, boxWidth) + 'px';
_divContextMenu.style.top = SetContextMenuVerticalPosition(pageHeight, pageYOffSet, boxYcooridnate, contextMenuHeight, boxHeight) + 'px';
ChangeOpacityForElement(100, _divContextMenu.id);
// chris edit - document.getElementById(_currentContextMenuId).firstChild.focus();
firstChildNoWS(document.getElementById(_currentContextMenuId)).focus();
}
}
// ***********************************
// Context menu keyboard navigation
// ***********************************
// Opens context menu via keyboard. Context menu
// is opened by selecting an item and pressing
// Alt + Down.
function OpenMenuKeyPress(e, contextMenuId)
{
// Alt key was pressed
if (e.altKey)
{
var keyCode;
if (window.event)
keyCode = e.keyCode;
else
keyCode = e.which;
// Down key was pressed
if (keyCode == 40)
{
// Open context menu.
Clicked(event, contextMenuId);
// Highlight the first selectable item
// in the context menu.
HighlightContextMenuItem(true);
}
}
}
// Performs keyboard navigation within
// opened context menu.
function NavigateMenuKeyPress(e)
{
var keyCode;
if (window.event)
keyCode = e.keyCode;
else
keyCode = e.which;
// Down key moves down to the next context menu item
if (keyCode == 40)
{
HighlightContextMenuItem(true);
}
// Up key moves up to the previous context menu item
else if (keyCode == 38)
{
HighlightContextMenuItem(false);
}
// Escape key closes context menu
else if (keyCode == 27)
{
// Close context menu
UnSelectedMenuItem();
// Make sure focus is given to the catalog item
// in the folder view.
document.getElementById(_selectedItemId).focus();
}
}
// Highlights context menu item.
// Parameter: highlightNext
// - If true, highlights menu item below current menu item.
// If current menu item is the last item, wraps around and
// highlights first menu item.
// - If false, highlights menu item above current menu item.
// If current menu item is the first item, wraps around and
// highlights last menu item.
function HighlightContextMenuItem(highlightNext)
{
var contextMenu = document.getElementById(_currentContextMenuId);
// chris edit - var table = contextMenu.lastChild;
var table = lastChildNoWS(contextMenu);
var currentMenuItemIndex = -1;
if (_currentMenuItemId != null)
currentMenuItemIndex = document.getElementById(_currentMenuItemId).parentNode.rowIndex;
var index = currentMenuItemIndex;
while (true)
{
if (highlightNext)
{
index++;
// If the index is out of range,
// reset it to the beginning
if (index < 0 || index >= table.cells.length)
index = 0;
}
else
{
index--;
// If the index is out of range,
// reset it to the end
if (index < 0 || index >= table.cells.length)
index = table.cells.length - 1;
}
// Each context menu item has an associated
// group ID. Make sure the table cell has a valid
// group ID, otherwise it is not a menu item (e.g.
// an underline separator).
if (table.cells[index].group >= 0)
{
FocusContextMenuItem(table.cells[index].id, 'msrs-MenuUIItemTableHover', 'msrs-MenuUIItemTableCell');
break;
}
// If we reach the orignal index, that means we looped
// through all table cells and did not find a valid context
// menu item. In that case, stop searching.
if (index == currentMenuItemIndex)
break;
}
}
// *** End keyboard navigation ***
// This function resets the context menus shape and size.
function ResetContextMenu() {
_divContextMenu.style.height = 'auto';
_divContextMenu.style.width = 'auto';
_divContextMenu.style.overflowY = 'visible';
_divContextMenu.style.overflowX = 'visible';
_divContextMenu.style.overflow = 'visible';
_divContextMenu.style.display = 'block';
}
// This function sets the horizontal position of the context menu.
// It also sets is the context menu has vertical scroll bars.
function SetContextMenuHorizonatalPosition(pageWidth, pageXOffSet, boxXcoordinate, contextMenuWidth, boxWidth) {
var menuXCoordinate = boxXcoordinate + boxWidth - contextMenuWidth;
var spaceRightBox = (pageWidth + pageXOffSet) - menuXCoordinate;
var spaceLeftBox = menuXCoordinate - pageXOffSet;
var returnValue;
if ((contextMenuWidth < spaceRightBox) && (pageXOffSet < menuXCoordinate)) {
returnValue = menuXCoordinate;
}
else if ((contextMenuWidth < spaceRightBox)) {
returnValue = pageXOffSet;
}
else if (contextMenuWidth < spaceLeftBox) {
returnValue = menuXCoordinate - (contextMenuWidth - (pageWidth + pageXOffSet - menuXCoordinate));
}
else {
_divContextMenu.style.overflowX = "scroll";
if (spaceLeftBox < spaceRightBox) {
_divContextMenu.style.width = spaceRightBox;
returnValue = pageXOffSet;
}
else {
_divContextMenu.style.width = spaceLeftBox;
returnValue = menuXCoordinate - (spaceLeftBox - (pageWidth + pageXOffSet - menuXCoordinate));
}
}
return returnValue;
}
// This function sets the vertical position of the context menu.
// It also sets is the context menu has horizontal scroll bars.
function SetContextMenuVerticalPosition(pageHeight, pageYOffSet, boxYcooridnate, contextMenuHeight, boxHeight) {
var spaceBelowBox = (pageHeight + pageYOffSet) - (boxYcooridnate + boxHeight);
var spaceAboveBox = boxYcooridnate - pageYOffSet;
var returnValue;
if (contextMenuHeight < spaceBelowBox) {
returnValue = (boxYcooridnate + boxHeight);
}
else if (contextMenuHeight < spaceAboveBox) {
returnValue = (boxYcooridnate - contextMenuHeight);
}
else if (spaceBelowBox > spaceAboveBox) {
_divContextMenu.style.height = spaceBelowBox;
_divContextMenu.style.overflowY = "scroll";
returnValue = (boxYcooridnate + boxHeight);
}
else {
_divContextMenu.style.height = spaceAboveBox;
_divContextMenu.style.overflowY = "scroll";
returnValue = (boxYcooridnate - spaceAboveBox);
}
return returnValue;
}
// This function displays a context menu given its id and then hides the others
function SelectContextMenuFromColletion(contextMenuConfigString) {
var contextMenuId = SplitContextMenuConfigString(contextMenuConfigString);
for (i = 0; i < _contextMenusIds.length; i++) {
var cm = document.getElementById(_contextMenusIds[i]);
if (cm.id == contextMenuId) {
cm.style.visibility = 'visible';
cm.style.display = 'block';
_currentContextMenuId = contextMenuId;
}
else {
cm.style.visibility = 'hidden';
cm.style.display = 'none';
}
}
}
function SplitContextMenuConfigString(contextMenuConfigString) {
var contextMenuEnd = contextMenuConfigString.indexOf(":");
var contextMenuId = contextMenuConfigString;
var contextMenuHiddenItems;
if (contextMenuEnd != -1)
{
contextMenuId = contextMenuConfigString.substr(0, contextMenuEnd);
}
var cm = document.getElementById(contextMenuId);
// chris edit - var table = cm.firstChild;
var table = firstChildNoWS(cm);
var groupItemCount = []; // The items in each group
var groupUnderlineId = []; // The Id's of the underlines.
// Enable all menu items counting the number of groups,
// number of items in the groups and underlines for the groups as we go.
// start chris edit
/* for (i = 0; i < table.cells.length; i++)
{
table.cells[i].style.visibility = 'visible';
table.cells[i].style.display = 'block'
if ((groupItemCount.length - 1) < table.cells[i].group) {
groupItemCount.push(1);
groupUnderlineId.push(table.cells[i].underline);
}
else {
groupItemCount[table.cells[i].group]++;
}
AlterVisibilityOfAssociatedUnderline(table.cells[i], true)
}*/
if (table != null && table.rows != null)
{
for (r = 0; r < table.rows.length; r++) {
for (i = 0; i < table.rows[r].cells.length; i++)
{
table.rows[r].cells[i].style.visibility = 'visible';
table.rows[r].cells[i].style.display = 'block'
if ((groupItemCount.length - 1) < table.rows[r].cells[i].group) {
groupItemCount.push(1);
groupUnderlineId.push(table.rows[r].cells[i].underline);
}
else {
groupItemCount[table.rows[r].cells[i].group]++;
}
AlterVisibilityOfAssociatedUnderline(table.rows[r].cells[i], true)
}
}
}
// end chris edit
// If hidden items are listed, remove them from the context menu
if (contextMenuEnd != -1)
{
contextMenuHiddenItems = contextMenuConfigString.substr((contextMenuEnd + 1), (contextMenuConfigString.length - 1)).split("-");
var groupsToHide = groupItemCount;
// Hide the hidden items
for (i = 0; i < contextMenuHiddenItems.length; i++)
{
var item = document.getElementById(contextMenuHiddenItems[i]);
item.style.visibility = 'hidden';
item.style.display = 'none'
groupsToHide[item.group]--;
}
var allHidden = true;
// Work back through the groups hiding the underlines as required.
for (i = (groupsToHide.length - 1); i > -1; i--) {
if (groupsToHide[i] == 0) {
AlterVisibilityOfAssociatedUnderline(groupUnderlineId[i], false);
}
else if (allHidden && i == (groupsToHide.length - 1)) {
allHidden = false;
}
// If all the items have been hidden so far hide the last underline too.
else if (allHidden) {
allHidden = false;
AlterVisibilityOfAssociatedUnderline(groupUnderlineId[i], false);
}
}
}
return contextMenuId;
}
function AlterVisibilityOfAssociatedUnderline(underLineId, visibility) {
if (underLineId != null && underLineId != "") {
var underlineElement = document.getElementById(underLineId);
if (underlineElement != null) {
if (visibility) {
underlineElement.style.visibility = 'visible';
underlineElement.style.display = 'block'
}
else {
underlineElement.style.visibility = 'hidden';
underlineElement.style.display = 'none'
}
}
}
}
function ClearTimeouts() {
if (_fadeTimeouts != null) {
for (i = 0; i < _fadeTimeouts.length; i++) {
clearTimeout(_fadeTimeouts[i]);
}
}
_fadeTimeouts = [];
}
// This function chnages an elements opacity given its id.
function FadeOutElement(id, opacStart, opacEnd, millisec) {
ClearTimeouts();
//speed for each frame
var speed = Math.round(millisec / 100);
var timer = 0;
for (i = opacStart; i >= opacEnd; i--) {
_fadeTimeouts.push(setTimeout("ChangeOpacityForElement(" + i + ",'" + id + "')", (timer * speed)));
timer++;
}
}
// This function changes the opacity of an elemnent given it's id.
// Works across browsers for different browsers
function ChangeOpacityForElement(opacity, id) {
var object = document.getElementById(id).style;
if (opacity != 0) {
// **Cross browser compatibility code**
object.opacity = (opacity / 100);
object.MozOpacity = (opacity / 100);
object.KhtmlOpacity = (opacity / 100);
object.filter = "alpha(opacity=" + opacity + ")";
}
else {
object.display = 'none';
}
}
// This function is the click for the body of the document
function ContextMouseDown() {
if (_mouseOverContext) {
return;
}
else {
HideMenu()
}
}
// This function fades out the context menu and then unselects the associated name control
function UnSelectedMenuItem() {
if (_itemSelected) {
FadeOutElement(_divContextMenu.id, 100, 0, 300);
UnselectCurrentMenuItem();
}
}
// Hides context menu without fading effect
function HideMenu()
{
if (_itemSelected)
{
ChangeOpacityForElement(0, _divContextMenu.id);
UnselectCurrentMenuItem();
}
}
function UnselectCurrentMenuItem()
{
_itemSelected = false;
_currentContextMenuId = null;
SwapStyle(_currentMenuItemId, 'msrs-MenuUIItemTableCell');
_currentMenuItemId = null;
ChangeReportItemStyle(_selectedItemId, "msrs-UnSelectedItem");
}
// This function walks back up the DOM tree until it finds the first occurrence
// of a given element. It then returns this element
function GetOuterElementOfType(element, type) {
while (element.tagName.toLowerCase() != type) {
element = element.parentNode;
}
return element;
}
// This function gets the corrdinates of the top left corner of a given element
function GetElementPosition(element) {
element = GetOuterElementOfType(element, 'table');
var left, top;
left = top = 0;
if (element.offsetParent) {
do {
left += element.offsetLeft;
top += element.offsetTop;
} while (element = element.offsetParent);
}
return { left: left, top: top };
}
function FocusContextMenuItem(menuItemId, focusStyle, blurStyle)
{
SwapStyle(_currentMenuItemId, blurStyle);
SwapStyle(menuItemId, focusStyle);
// chrid edit - document.getElementById(menuItemId).firstChild.focus();
firstChildNoWS(document.getElementById(menuItemId)).focus();
_currentMenuItemId = menuItemId;
}
// This function swaps the style using the id of a given element
function SwapStyle(id, style) {
if (document.getElementById) {
var selectedElement = document.getElementById(id);
if (selectedElement != null)
{
selectedElement.className = style;
}
}
}
// This function changes the style using the id of a given element
// and should only be called for catalog items in the tile or details view
function ChangeReportItemStyle(id, style)
{
if (!_itemSelected)
{
if (document.getElementById)
{
var selectedElement = document.getElementById(id);
selectedElement.className = style;
// Change the style on the end cell by drilling into the table.
if (selectedElement.tagName.toLowerCase() == "table")
{
// chris edit - var tbody = selectedElement.lastChild;
var tbody = lastChildNoWS(selectedElement);
if (tbody != null)
{
// chris edit - var tr = tbody.lastChild;
var tr = lastChildNoWS(tbody);
if (tr != null)
{
// chris edit - tr.lastChild.className = style + 'End';
trLastChild = lastChildNoWS(tr);
if (trLastChild != null)
{
trLastChild.className = style + 'End';
}
}
}
}
}
}
}
function ChangeReportItemStyleOnFocus(id, currentStyle, unselectedStyle)
{
_unselectedItemStyle = unselectedStyle;
_tabFocusedItem = id;
// We should unselect selected by mouse over item if there is one
if(_mouseOverItem != '')
{
ChangeReportItemStyle(_mouseOverItem, _unselectedItemStyle);
_mouseOverItem = '';
}
ChangeReportItemStyle(id, currentStyle);
}
function ChangeReportItemStyleOnBlur(id, style)
{
ChangeReportItemStyle(id, style);
_tabFocusedItem = '';
}
function ChangeReportItemStyleOnMouseOver(id, currentStyle, unselectedStyle)
{
_unselectedItemStyle = unselectedStyle;
_mouseOverItem = id;
// We should unselect tabbed item if there is one
if(_tabFocusedItem != '')
{
ChangeReportItemStyle(_tabFocusedItem, _unselectedItemStyle);
_tabFocusedItem = '';
}
ChangeReportItemStyle(id, currentStyle);
}
function ChangeReportItemStyleOnMouseOut(id, style)
{
ChangeReportItemStyle(id, style);
_mouseOverItem = '';
}
// This function is used to set the style of the search bar on the onclick event.
function SearchBarClicked(id, defaultText, style) {
var selectedElement = document.getElementById(id);
if (selectedElement.value == defaultText) {
selectedElement.value = "";
selectedElement.className = style;
}
}
// This function is used to set the style of the search bar on the onblur event.
function SearchBarBlured(id, defaultText, style) {
var selectedElement = document.getElementById(id);
if (selectedElement.value == "") {
selectedElement.value = defaultText;
selectedElement.className = style;
}
}
function ResetSearchBar(searchTextBoxID,defaultSearchValue) {
var selectedElement = document.getElementById(searchTextBoxID);
if (selectedElement != null) {
if (selectedElement.value == defaultSearchValue) {
selectedElement.className = 'msrs-searchDefaultFont';
}
else {
selectedElement.className = 'msrs-searchBarNoBorder';
}
}
}
function OnLink()
{
_onLink = true;
}
function OffLink()
{
_onLink = false;
}
function ShouldDelete(confirmMessage) {
if (_selectedIdHiddenField.value != null || _selectedIdHiddenField.value != "") {
var message = confirmMessage.replace("{0}", _selectedIdHiddenField.value);
var result = confirm(message);
if (result == true) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
function UpdateValidationButtonState(promptCredsRdoBtnId, typesDropDownId, forbiddenTypesConfigString, validateButtonId)
{
var dropdown = document.getElementById(typesDropDownId);
if(dropdown == null)
{
return;
}
var selectedValue = dropdown.options[dropdown.selectedIndex].value;
var forbiddenTypes = forbiddenTypesConfigString.split(":");
var chosenForbiddenType = false;
for (i = 0; i < forbiddenTypes.length; i++)
{
if(forbiddenTypes[i] == selectedValue)
{
chosenForbiddenType = true;
}
}
var isDisabled = chosenForbiddenType || IsRadioButtonChecked(promptCredsRdoBtnId);
ChangeDisabledButtonState(validateButtonId, isDisabled);
}
function ChangeDisabledButtonState(buttonId, isDisabled)
{
var button = document.getElementById(buttonId);
if(button != null)
{
button.disabled = isDisabled;
}
}
function IsRadioButtonChecked(radioButtonId)
{
var rbtn = document.getElementById(radioButtonId);
if(rbtn != null && rbtn.checked)
{
return true;
}
return false;
}

Basic JS + WebDev help

I have a little Problem. I have seven <select>'s. The go from left to right counting up.
<select id="sel_1" onchange="evalonsubmit('sel_1',1);">
<select id="sel_2" onchange="evalonsubmit('sel_2',2);">
That goes from 1 to 7 in this way.
The logic is easy. On click check if the value is -1 if it is disable everything on the right and set it to -1. if it is not -1 then enable the the right of the clicked one (+1 so to say)
And that's the code:
function evalonsubmit(ID, n)
{
var ElementID = document.getElementById(ID);
if(ElementID.value = -1) {
for (var i = n + 1; i <= 7; i++){
var newID = "sel_" + i;
var newValue = document.getElementById();
newValue.disable = true;
newValue.value = -1
}
} else {
var newID = "sel_"+(n+1)
var newValue = document.getElementById();
newValue.disable = false;
}
}
Can somebody kind JS hacker help me?
I just fixed some simple mistakes in your code ..
function evalonsubmit(ID, n)
{
var ElementID = document.getElementById(ID);
if (ElementID.value == -1){
for (var i=n+1; i <= 7; i++){
var newID = "sel_" + i;
var newValue = document.getElementById(newID);
newValue.disable = true;
newValue.value = -1
}
} else {
var newID = "sel_"+(n+1)
var newValue = document.getElementById(newID);
newValue.disable = false;
}
}
Not quite sure what you want, but it probably should be:
if (ElementID.value == -1){
// ^--- two = , otherwise you assign the value
and
var newID = "sel_" + i;
var newValue = document.getElementById(newID);
// pass parameter ---^
Same in the else branch.
Besides that, I would give your variables more meaningful names. E.g. ElementID lets you assume that the value is an ID. But it is not. It is a DOM element. Same for newValue.
You're missing the parameter in a couple of your calls to document.getElementById, and the property for disabling a <select> is disabled, not disable. You also have = where you need ==.
function evalonsubmit(ID, n)
{
var ElementID = document.getElementById(ID);
if (ElementID.value == -1){
for (var i=n+1; i <= 7; i++){
var newID = "sel_" + i;
var newValue = document.getElementById(newID);
newValue.disabled = true;
newValue.value = -1;
}
} else {
var newID = "sel_"+(n+1);
var newValue = document.getElementById(newID);
newValue.disabled = false;
}
}
Why not do this:
HTML:
<div class="wrapper">
<select onchange="evalonsubmit(this);" />
<select onchange="evalonsubmit(this);" />
<select onchange="evalonsubmit(this);" />
</div>
JS:
function nextElement(current)
{
do
current = current.nextSibling;
while (current && current.nodeType != 1);
return current;
}
function evalonsubmit(elem)
{
if(elem.value == -1)
while(elem = nextElement(elem)) {
elem.disabled = true;
elem.value = -1
}
else if(elem = nextElement(elem))
elem.disabled = false;
}
That removes the need for ids on the <select> elements, as following elements can be grabbed with .nextSibling. The nextElement() function is to avoid grabbing text nodes.

Categories

Resources