Is there a polyfill for findAll - javascript

I am using JavaScript findAll for a selector engine. Is there any polyfill for the findAll function. I tried to create my own selector engine with this code:
function CTfind(string, context){
var result = [], finalResult = [];
if(typeof string === "object"){
result.push(string);
return result;
}
if(/<([a-zA-Z]+)(\s*)?\/>/ig.test(string)){
var str = string.replace(/<([a-zA-Z]+)(\s*)?\/>/ig, "$1");
var ret = document.createElement(str);
if(typeof context === "object"){
for(i in context)
ret[i] = context[i];
}
document.body.appendChild(ret);
result.push(ret);
return result;
} else{
if(typeof string !== "string" && typeof string !== "object") return false;
var documentElements = context.getElementsByTagName("*"),
toMatch = string.split(", ");
for(i = 0; i < documentElements.length; i++){
for(e = 0; e < toMatch.length; e++){
var stringParts = toMatch[e].split(" ");
for(s = 0; s < stringParts.length; s++){
var parts;
if(/(\.|\#|\:)/g.test(stringParts[s])){
parts = stringParts[s].match(/([A-Za-z]+|[\.\#\:]+[^\.\#\:]+)/g);
} else if(/^(?!(\.|\#|\:)$).*$/g.test(stringParts[s])){
parts = stringParts[s];
var onlyElem = true;
}
if(onlyElem === true){
console.log(documentElements[i].nodeName);
if(documentElements[i].nodeName.toLowerCase() === parts){
result.push(documentElements[i]);
}
} else{
var containsClass = false,
containsElem = false,
containsID = false,
containsPseudo = false,
matchID = false,
matchElem = false,
matchClass = false,
matchPseudo = false;
if(/\./.test(stringParts[s])){
containsClass = true;
}
if(/\#/.test(stringParts[s])){
containsID = true;
}
if(/\:/.test(stringParts[s])){
containsPseudo = true;
}
if(/[^\.\#\:](.*)/.test(stringParts[s])){
containsElem = true;
}
if(containsElem === true){
var elem;
for(g = 0; g < parts.length; g++){
if(/^([^\.\#\:][A-Za-z])*$/.test(parts[g])){
elem = parts[g];
} else{
elem = documentElements[i].nodeName.toLowerCase();
}
}
if(documentElements[i].nodeName.toLowerCase() === elem){
matchElem = true;
}
} else{
matchElem = true;
}
if(containsID === true){
var id = filter(parts, "#");
id = id[0].substr(1);
if(getAttr(documentElements[i], "id") === id){
matchID = true;
}
} else{
matchID = true;
}
if(containsClass === true){
var classes = filter(parts, ".");
if(typeof classes === "string"){
classes = classes[0].split(".");
for(c = 0; c < classes.length; c++){
if(classes[c] !== ""){
if(hasClass(documentElements[i], classes[c])){
matchClass = true;
}
}
}
}
} else{
matchClass = true;
}
if(matchClass && matchID && matchElem){
result.push(documentElements[i]);
}
console.log(result);
}
}
if(stringParts.length > 1){
console.log(result);
if(isDescendant(result[0], result[result.length - 1])){
finalResult.push(result[result.length - 1]);
}
}
}
}
return finalResult;
}
};
But I thought using Javascript findAll would be much easier. Also, I can't use querySelector because sometimes I need to find it in a specific node.

Related

Javascript condition not working as expected

I have a JS code which works fine when
checkQueryString != "M"
but When the value becomes checkQueryString == "M" it doesn't goes inside the loop
Here is my code.
function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
if(checkQueryString == "M")
{
alert('Value is M now');
}
else {
alert('Kindly select the stage');
}
}
}
So my question is, why it doesn't goes inside if when it matches to M
Because
if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
Has inside if (checkQueryString == "M")
So try this
function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
} else if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
}

Javascript in_array

In php this is a nice way of asking is a value is one of a few options
if( in_array($needle, [1,325,'something else']) ){
//do your thing
}
But in the world of javascript is there an equiv. that doesn't require writing a bespoke function such as:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
Use case of the above js bespoke function
if( inArray( somvar, [1,2,'something else']) ){
do the javascript thing
}
FROM THE COMMENTS
this is the most accurate answer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
var needle = 325;
if( [1,325,'something else'].indexOf(needle) !== -1 ){
//do your thing
};
You can use Array.prototype.find():
var data = ['Lorem', 'Ipsum', 'Sit']
var foundSit = data.find(function(item){
return item == 'Sit';
});

Using the input box instead of pop function

How can I use an input box instead of prompt on this code?
Code is
here.
Once I click on the link; a prompt pops up and asks to type a number or Q to quit. How would I change that to input box?
function Stack() {
var items = [];
this.push = function(element){
items.push(element);
};
this.pop = function(){
return items.pop();
};
this.peek = function(){
return items[items.length-1];
};
this.isEmpty = function(){
return items.length == 0;
};
this.size = function(){
return items.length;
};
this.clear = function(){
items = [];
};
this.print = function(){
alert("Stack Elements are:"+items.toString());
};
}
Declare stack object:
var stack = new Stack();
while(1)
{
var element = prompt("Enter stack element,(q or Q to exit)", "");
if(element == 'q' || element =='Q')
{
break;
}
else
{
if(element=='*'
|| element=='+' || element=='-' || element=='/')
{
//Check if stack is empty
if(stack.isEmpty() || stack.size<2 )
{
alert("Invalid Operation, Stack is empty or size is less than 2");
}
else
{
var op1 = stack.pop();
var op2 = stack.pop();
if(element=='*')
{
var res = op1 * op2;
}
else if(element=='+')
{
var res = op1 + op2;
}
else if(element=='-')
{
var res = op1 - op2;
}
else if(element=='/')
{
var res = op1 / op2;
}
stack.push(res);
stack.print();
}
}
else
{
stack.push(element);
stack.print();
}
}
}
try following example :
FIDDLE
var stack = new Stack();
function Stack() {
var items = [];
this.push = function(element) {
items.push(element);
};
this.pop = function() {
return items.pop();
};
this.peek = function() {
return items[items.length - 1];
};
this.isEmpty = function() {
return items.length == 0;
};
this.size = function() {
return items.length;
};
this.clear = function() {
items = [];
};
this.print = function() {
theList.options.length = 0;
for (var i = 0; i < items.length; i++) {
var theOption = new Option(items[i]);
theList.options[theList.options.length] = theOption;
}
};
}
function pushStack(newVal) {
if (newVal == '*' || newVal == '+' || newVal == '-' || newVal == '/') {
//Check if stack is empty
if (stack.isEmpty() || stack.size < 2) {
alert("Invalid Operation, Stack is empty or size is less than 2");
} else {
var op1 = stack.pop();
var op2 = stack.pop();
if (newVal == '*') {
var res = op1 * op2;
} else if (newVal == '+') {
var res = op1 + op2;
} else if (newVal == '-') {
var res = op1 - op2;
} else if (newVal == '/') {
var res = op1 / op2;
}
stack.push(res);
}
} else {
stack.push(newVal);
}
}
function popStack() {
var popVal = stack.pop();
if (popVal == undefined)
return "Empty stack!";
else
return popVal;
}
function showStack() {
stack.print();
}
<FORM>
<INPUT type="text" name="txtPush" id="txtPush" />
<INPUT type=button value="Push" onClick='pushStack(txtPush.value); txtPush.value=""; showStack(theList);' />
<SELECT name="theList" id="theList" size=12>
<OPTION>Displays the current state of the stack!</OPTION>
</SELECT>
</FORM>

Tic Tac Toe with Minimax and Javascript

I am attempting to create a Tic Tac Toe game using Javascript as part of my learning on FreeCodeCamp and after my 5th attempt still haven't managed to get it to work. I think i'm doing the correct thing, but the computer AI is still making very stupid decisions and loosing.
Here is my entire AI function, which can be called using a console log to see the recommended move from the AI. However when i hard code values for moves already taken and ask for the next move, it doesn't pick what i would expect.
/*
Attempt to inplement a Tic Tac Toe minimax game
5th attempt, so hopefully this time it works!
*/
var util = require("util");
//These are all the winning square sequences, as string to make various things easier
var validRows = [
['00','01','02'], // left column
['10','11','12'], // middle column
['20','21','22'], // right column
['00','10','20'], // top row
['01','11','21'], // middle row
['02','12','22'], // bottom row
['00','11','22'], // Diag TL to BR
['20','11','02'] // Diag BL to TR
];
//Our scoring arrays for evaulating moves
var max1 = ['100','010','001'];
var min1 = ['200','020','002'];
var max2 = ['110','011'];
var min2 = ['220','022'];
var max3 = ['111'];
var min3 = ['222'];
//All the valid squares
var validSquaresFactory = ['00','10','20','01','11','21','02','12','22'];
//Store all the moves somewhere
//var computerMoves = ['10','22'];
//var userMoves = ['00','02'];
//Store all the moves somewhere
var computerMoves = ['11','22'];
var userMoves = ['00','01'];
function Board(minOrMax,computerMoves,userMoves){
this.computer = computerMoves;
this.user = userMoves;
this.minOrMax = minOrMax;
this.remaining = this.genRemaining();
this.complete = this.genComplete();
var results = this.getScore();
this.score = results[0];
this.winOrLoose = results[1];
}
Board.prototype.genRemaining = function(){
//Create an array of all moves taken
var takenMoves = this.computer.concat(this.user);
//Calculate all remaining squares
var validSquares = validSquaresFactory.filter(function(object){
return takenMoves.indexOf(object) === -1;
});
return validSquares;
}
Board.prototype.genComplete = function(){
return ((this.computer.length + this.user.length) === 9);
}
Board.prototype.flipMinOrMax = function(){
return (this.minOrMax === 'max') ? 'min' : 'max'
}
Board.prototype.genArrays = function(minOrMax,square){
var tempUser = this.user.slice(0);
var tempComputer = this.computer.slice(0);
if(minOrMax === 'min'){
tempUser.push(square);
} else {
tempComputer.push(square);
}
return [tempComputer,tempUser];
}
Board.prototype.generateBoards = function(minOrMax){
var boards = [];
var that = this;
this.remaining.forEach(function(remainingSquare){
var moves = that.genArrays(minOrMax,remainingSquare);
boards.push(new Board(minOrMax,moves[0],moves[1]));
})
//console.log(boards);
return boards;
}
Board.prototype.getScore = function(){
var that = this;
var winOrLoose = false;
var returnScore = validRows.reduce(function(storage,row,index,array){
var score = row.reduce(function(storage1,square){
if (that.computer.indexOf(square) !== -1) {
storage1 += '1';
} else if (that.user.indexOf(square) !== -1) {
storage1 += '2';
} else {
storage1 += '0';
}
return storage1;
},'')
var finalScore = 0;
if(max1.indexOf(score) != -1){
finalScore = 1;
} else if(min1.indexOf(score) != -1){
finalScore = -1;
} else if(max2.indexOf(score) != -1){
finalScore = 10;
} else if(min2.indexOf(score) != -1){
finalScore = -10;
} else if(max3.indexOf(score) != -1){
winOrLoose = true;
finalScore = 100;
} else if(min3.indexOf(score) != -1){
winOrLoose = false;
finalScore = -100;
}
storage.push(finalScore);
return storage;
},[])
var condensedReturnScore = returnScore.reduce(function(storage,score){
return storage+score;
})
return [condensedReturnScore,winOrLoose];
}
function generateMove(){
var board = new Board('max',computerMoves,userMoves);
var scores = [];
var boards = board.generateBoards('max');
boards.forEach(function(board){
scores.push(testMove(board,4));
});
scores = scores.map(function(score,index){
return [board.remaining[index],score];
});
var returnValue = scores.reduce(function(storage,score){
return (score[1].score > storage[1].score) ? score : storage;
});
return [returnValue[0],returnValue[1].score];
}
function testMove(masterBoard,count){
count --;
var boards = [];
boards = masterBoard.generateBoards(generateMinOrMax(masterBoard.minOrMax));
//console.log('/////////Master Board/////////');
//console.log(masterBoard);
//console.log(boards);
//console.log('//////////////////////////////');
boards = boards.map(function (move) {
if (move.complete === true || count === 0 || move.winOrLoose === true){
return move;
} else {
var returnScore = testMove(move,count);
return returnScore;
}
});
returnBoard = boards.reduce(function(storage,board,index,array){
if(board.minOrMax === 'max'){
return (board.score > storage.score) ? board : storage;
} else {
return (board.score < storage.score) ? board : storage;
}
});
return returnBoard;
}
function generateMinOrMax(minOrMax){
return (minOrMax === 'max') ? 'min' : 'max'
}
I've checked the scoring function and from what i can see it is returning the expected score for any move i try, but because of the shear number of possibilities calculated it's very hard to debug efficiently.
Any help/pointers on this would be most appreciated as i have really hit a brick wall with this, can't see the forrest for the trees e.t.c
If you would like to test this with the GUI, it's on codepen at - http://codepen.io/gazzer82/pen/yYZmvJ?editors=001
So after banging my head against this for day, as soon as i posted this i found the issues. Firstly using the wrong variable for minormax in my reduce function, so it wasn't flipping correctly and not setting the winOrLoose value correctly for a score of -100. Here is the corrected version.
*
Attempt to inplement a Tic Tac Toe minimax game
5th attempt, so hopefully this time it works!
*/
var util = require("util");
//These are all the winning square sequences, as string to make various things easier
var validRows = [
['00','01','02'], // left column
['10','11','12'], // middle column
['20','21','22'], // right column
['00','10','20'], // top row
['01','11','21'], // middle row
['02','12','22'], // bottom row
['00','11','22'], // Diag TL to BR
['20','11','02'] // Diag BL to TR
];
//Our scoring arrays for evaulating moves
var max1 = ['100','010','001'];
var min1 = ['200','020','002'];
var max2 = ['110','011'];
var min2 = ['220','022'];
var max3 = ['111'];
var min3 = ['222'];
//All the valid squares
var validSquaresFactory = ['00','10','20','01','11','21','02','12','22'];
//Store all the moves somewhere
//var computerMoves = ['10','22'];
//var userMoves = ['00','02'];
//Store all the moves somewhere
var computerMoves = ['00','20','01'];
var userMoves = ['10','11','02'];
//01,21,22 - 01//
function Board(minOrMax,computerMoves,userMoves){
this.computer = computerMoves;
this.user = userMoves;
this.minOrMax = minOrMax;
this.remaining = this.genRemaining();
this.complete = this.genComplete();
var results = this.getScore();
this.score = results[0];
this.winOrLoose = results[1];
}
Board.prototype.genRemaining = function(){
//Create an array of all moves taken
var takenMoves = this.computer.concat(this.user);
//Calculate all remaining squares
var validSquares = validSquaresFactory.filter(function(object){
return takenMoves.indexOf(object) === -1;
});
return validSquares;
}
Board.prototype.genComplete = function(){
return ((this.computer.length + this.user.length) === 9);
}
Board.prototype.flipMinOrMax = function(){
return (this.minOrMax === 'max') ? 'min' : 'max'
}
Board.prototype.genArrays = function(minOrMax,square){
var tempUser = this.user.slice(0);
var tempComputer = this.computer.slice(0);
if(minOrMax === 'min'){
tempUser.push(square);
} else {
tempComputer.push(square);
}
return [tempComputer,tempUser];
}
Board.prototype.generateBoards = function(minOrMax){
var boards = [];
var that = this;
this.remaining.forEach(function(remainingSquare){
var moves = that.genArrays(minOrMax,remainingSquare);
boards.push(new Board(minOrMax,moves[0],moves[1]));
})
//console.log(boards);
return boards;
}
Board.prototype.getScore = function(){
var that = this;
var winOrLoose = false;
var returnScore = validRows.reduce(function(storage,row,index,array){
var score = row.reduce(function(storage1,square){
if (that.computer.indexOf(square) !== -1) {
storage1 += '1';
} else if (that.user.indexOf(square) !== -1) {
storage1 += '2';
} else {
storage1 += '0';
}
return storage1;
},'')
var finalScore = 0;
if(max1.indexOf(score) != -1){
finalScore = 1;
} else if(min1.indexOf(score) != -1){
finalScore = -1;
} else if(max2.indexOf(score) != -1){
finalScore = 10;
} else if(min2.indexOf(score) != -1){
finalScore = -10;
} else if(max3.indexOf(score) != -1){
winOrLoose = true;
finalScore = 100;
} else if(min3.indexOf(score) != -1){
winOrLoose = true;
finalScore = -100;
}
storage.push(finalScore);
return storage;
},[])
var condensedReturnScore = returnScore.reduce(function(storage,score){
return storage+score;
})
return [condensedReturnScore,winOrLoose];
}
function generateMove() {
var board = new Board('max', computerMoves, userMoves);
if (board.remaining.length === 1) {
return [board.remaining[0], 0];
} else {
var scores = [];
var boards = board.generateBoards('max');
boards.forEach(function (board) {
scores.push(testMove(board, 4));
});
scores = scores.map(function (score, index) {
return [board.remaining[index], score];
});
var returnValue = scores.reduce(function (storage, score) {
return (score[1].score > storage[1].score) ? score : storage;
});
return [returnValue[0], returnValue[1].score];
}
}
function testMove(masterBoard,count){
count --;
var boards = [];
boards = masterBoard.generateBoards(generateMinOrMax(masterBoard.minOrMax));
boards = boards.map(function (move) {
if (move.complete === true || count <= 0 || move.winOrLoose === true){
return move;
} else {
var returnScore = testMove(move,count);
return returnScore;
}
});
returnBoard = boards.reduce(function(storage,board,index,array){
if(generateMinOrMax(masterBoard.minOrMax) === 'max'){
return (board.score > storage.score) ? board : storage;
} else {
return (board.score < storage.score) ? board : storage;
}
});
return returnBoard;
}
function generateMinOrMax(minOrMax){
return (minOrMax === 'max') ? 'min' : 'max'
}
function getScore(user,computer,minOrMax){
var that = this;
that.computer = computer;
that.user = user;
that.minOrMax = minOrMax;
var returnScore = validRows.reduce(function(storage,row,index,array){
var score = row.reduce(function(storage1,square){
if (that.computer.indexOf(square) !== -1) {
storage1 += '1';
} else if (that.user.indexOf(square) !== -1) {
storage1 += '2';
} else {
storage1 += '0';
}
return storage1;
},'')
var finalScore = 0;
if(max1.indexOf(score) != -1){
finalScore = 1;
} else if(min1.indexOf(score) != -1){
finalScore = -1;
} else if(max2.indexOf(score) != -1){
finalScore = 10;
} else if(min2.indexOf(score) != -1){
finalScore = -10;
} else if(max3.indexOf(score) != -1){
finalScore = 100;
} else if(min3.indexOf(score) != -1){
finalScore = -100;
}
storage.push(finalScore);
return storage;
},[])
var condensedReturnScore = returnScore.reduce(function(storage,score){
if(that.minOrMax === 'max'){
return (score >= storage) ? score : storage;
} else {
return (score <= storage) ? score : storage;
}
})
return condensedReturnScore;
}

JS/JSp issue in IE 10 for scrollbar and sorting

I am facing issue in table where we are using scroll bar and sorting.
In compatible mode sorting option is coming where as not coming in non compatible mode
Please suggest changes in js or jsp
function makeScrollableTable(tbl, scrollFooter, height, hasSelectAllButton, hasAddButton, columnNo) {
var c, pNode, hdr, ftr, wrapper, rect;
//alert("Shree");
if (typeof tbl == 'string') tbl = document.getElementById(tbl);
pNode = tbl.parentNode;
fixTableWidth(tbl);
c = container.length;
container[c] = document.createElement('<SPAN style="height: 100; overflow: auto;">');
container[c].id = tbl.id + "Container";
pNode.insertBefore(container[c], tbl);
container[c].appendChild(tbl);
container[c].style.width = tbl.clientWidth + 2 * tbl.clientLeft + scrollbarWidth();
hdr = tbl.cloneNode(false);
hdr.id += 'Header';
hdr.appendChild(tbl.tHead.cloneNode(true));
tbl.tHead.style.display = 'none';
if (!scrollFooter || !tbl.tFoot) {
ftr = document.createElement('<SPAN style="width:1;height:1;clip: rect(0 1 1 0);background-color:transparent;">');
ftr.id = tbl.id + 'Footer';
ftr.style.border = tbl.style.border;
ftr.style.width = getActualWidth(tbl) + 2 * tbl.clientLeft;
ftr.style.borderBottom = ftr.style.borderLeft = ftr.style.borderRight = 'none';
} else {
ftr = tbl.cloneNode(false);
ftr.id += 'Footer';
ftr.appendChild(tbl.tFoot.cloneNode(true));
ftr.style.borderTop = 'none';
tbl.tFoot.style.display = 'none';
}
wrapper = document.createElement('<table border=0 cellspacing=0 cellpadding=0>');
wrapper.id = tbl.id + 'Wrapper';
pNode.insertBefore(wrapper, container[c]);
wrapper.insertRow(0).insertCell(0).appendChild(hdr);
wrapper.insertRow(1).insertCell(0).appendChild(container[c]);
wrapper.insertRow(2).insertCell(0).appendChild(ftr);
wrapper.align = tbl.align;
tbl.align = hdr.align = ftr.align = 'left';
hdr.style.borderBottom = 'none';
tbl.style.borderTop = tbl.style.borderBottom = 'none';
// adjust page size
if (c == 0 && height == 'auto') {
onResizeAdjustTable();
onResizeHandler = window.onresize;
window.onresize = onResizeAdjustTable;
} else {
container[c].style.height = height;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
//alert("");
if (hasSelectAllButton) {
//include select all button
var selButton = document.createElement('<input id="_myButton11" type="button" value="Select All" onClick="selectAll();">');
insertNode(selButton);
}
if (hasAddButton) {
var btext = '<input id="_myButton12" type="button" value="Add" onClick="posCursor(\'' + tbl.id + '\',\'' + columnNo + '\');">';
var addButton = document.createElement(btext);
insertNode(addButton);
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function insertNode(toInsert) {
var tbs = document.getElementsByTagName('input');
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "button") {
var backButton = tbs[i];
var text = backButton.value.toUpperCase();
if (text == "BACK") {
var pNode = backButton.parentNode;
pNode.insertBefore(toInsert, backButton);
var textNode = document.createTextNode(" ");
pNode.insertBefore(textNode, backButton);
return;
}
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function posCursor(tbl, columnNo) {
var table = document.getElementById(tbl);
var rows = table.rows;
for (var i = 0; i < rows.length; i++) {
//cells = rows[i].cells;
//if(columnNo > cells.length) continue;
var cell = rows[i].cells[columnNo];
if (getFocus(cell) == true) {
selectCheckBox(rows[i].cells[0]);
return;
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectCheckBox(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a checkbox input node
if (node.tagName == "INPUT" && node.type == "checkbox") {
node.checked = true;
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (selectCheckBox(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function getFocus(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a text input node
if (node.tagName == "INPUT" && node.type == "text" && node.value == "") {
node.focus();
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (getFocus(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectAll() {
//added by Venkatesh Bhat e-mail:vb106#dcx
var button = document.getElementById('_myButton11');
var butText = button.value;
var tbs = document.getElementsByTagName('input');
if (butText == 'Deselect All') {
button.value = "Select All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = false;
}
}
} else {
button.value = "Deselect All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = true;
}
}
}
}
function onResizeAdjustTable() {
if (onResizeHandler) onResizeHandler();
var rect = container[0].getClientRects()(0);
var h = document.body.clientHeight - (rect.top + (document.body.scrollHeight - rect.bottom));
container[0].style.height = (h > 0) ? h : 1;
}
function printPage() {
var tbs = document.getElementsByTagName('TABLE');
var e;
for (var i = 0; i < container.length; i++) container[i].style.overflow = '';
window.print();
for (var i = 0; i < container.length; i++) container[i].style.overflow = 'auto';
}

Categories

Resources