Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sunday, March 21, 2021

Javascript Listening for a specific Key press

 If you want to know what key was press in a web page, you will normally do a document.addEventListener('keydown',myFunc) function. However, if you only want to act upon s specific key then the situation is slightly different becauses addEventListener does not have function to return anything.

Fortunately, there is a "bind" function in the event listener. by defining the event listener as

document.addEventListener('keydown',myFunc.bind(event))

In myFunc then you could use event.keyCode to determine which key was pressed and bypass any other.

There is an issue here. You can't capture key combinations. Keys like Alt-s will be passed as two event instead of one thus the function is triggered twice. But for just a simple key press like pressing the space-bar, the script works quite well.





Friday, February 24, 2017

Barcodes in Filemaker

When you need to print Barcodes in Filemaker, there are various ways to do it. One way is to use the "repetition" in the field. Each repetition represents a bar or blank. Set the width to 1.  Change the background to black if it is a bar. Obviously, you need to systematically convert the text to the specific type of barcodes first in the form of 1 and 0 then transpose it to the repetition field. It takes two extra fields. One to do the conversion, the other one with the repetition is used to display the barcode. Unfortunately you can't have GS1 HRI (Human Readable Integration).

Another method is to generate the barcode from a script. There are implementations available using plugins (because they want to sell the code). I can't find one that is free.

One other methods uses web views to display the barcode by passing a barcode generator site URL with parameters. However, this requires online access.

Yet another method uses data URL to achieve it. The web page that could create the Barcode using Javascript is stored in a hidden layout object. The data URL then reads the content and replaces a specific string in the web page with the text to be displayed in barcode. In the same way the parameters for the Barcode can also be changed. One good example is FMEasyBarcode. Unfortunately the author no longer maintains the code.

The following is an effort to try to do the same thing as David Shim.

First you need to have a webview object that contains the following script

Let([$html=Substitute(GetLayoutObjectAttribute("QRCode";"content"); ["[[VALUE]]"; mytable::userid)];["[[barcodetype]]";"qrcode"]];"data:text/html," & $html)

In layman's term, get the content of the object "QRCode" then substitute "[[VALUE]]" with mytable::userid (field value). Also substitute "[[barcodetype]]" with the barcode type called "qrcode".

In the hidden object, a complete single page HTML with Javascript is pasted into the content.  This HTML page must not have links that refers to local file (e.g script source). It can of course refer to external URL script source. What David Shim did is to copy the uglyfy js (all extra spaces,tabs,CRLF are removed) and paste into a javascript element. This is done to make sure the HTML have the smallest size.

Since the calculation is using Javascript, the replacement script in the webview will effectively change the data to be processed and run upon loading to produce the barcode. Obviously, that web page should work in normal browser.

I have tried the same method with a code39 script JsBarCode from Johan Lindell. It works fine.

One thing to note is that the size of the display is not by the webview.  I tried to add CSS to automatically resize the element but it just don't work. Some barcode does have a parameter to change the size. You will still gets some white space unless you specifically set the CSS to absolute position and define the top and left coordinate of the element.

One irritating thing is that the hidden object size tends to automatically expand if you try to edit it. But it is a small price to pay unless you want to store the HTML is a global field.

There is no script to show except the one line script mentioned above. The web page content is from other authors. I have included their project page for you to see how it works. David Shim's excellent qrcode project is at QRCodeJS.




Wednesday, December 15, 2010

JH-JS-CLASS

Decided to post the whole Javascript class on to Sourceforge. Posting it here is not so convenient as the postings cannot allow for <,>, and &. Moreover, when user copied the codes, it might cause problems if the text copied breaks the code by inserting newline character.

In future, I will describe the code here and leave the code at sourceforge if the codes are some library I created and added to the basic_class.js file. The URL is http://sourceforge.net/projects/jh-js-class/

Tuesday, December 14, 2010

Calendar PopUp

There has been quite a number of Javascript Calendar PopUp available in the internet. Many of them are very professionally made. However, I seems to have trouble using them. They either do not work out-of-the-box or needs a few settings here and there to function properly.

What I wanted is to have a very simple utility that allows me to choose a date in a limited format. I do not want to have too many settings. My habit is always to make life easy for programmers by not bothering them with too much options in my library.

The following is my version of a CalendarPopUp.

var $cP=function(myid,query2,query3){
// must set the id value of the date input element to work properly
// call the funcstion and pass the id value and type (MDY,DMY or YMD). query3 is not user definable
//remember to set the date input element to read only
var months=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
if (typeof(query3) != "undefined"){
var odate=query3.split("-")
var curdate=new Date(odate[0],odate[1],odate[2],0,0,0,0)
}
else
var curdate=new Date()
var curmth=curdate.getMonth()+1
var curyr=curdate.getFullYear()
var x,y
fdm=new Date(curdate.getFullYear(),curdate.getMonth(),1,0,0,0,0)
if(fdm.getMonth() !=0)
ldm=fdm.getFullYear()+"-"+(fdm.getMonth()-1)+"-"+fdm.getDate()
else
ldm=(fdm.getFullYear()-1)+"-11-"+fdm.getDate()
ndm=fdm.getFullYear()+"-"+(fdm.getMonth()+1)+"-"+fdm.getDate()
fdm.setDate(fdm.getDay()*-1)
var $winP=window.open("","cP","toolbar=0,location=0,drectories=0,menubar=0,scrollbars=0,resizable=0,width=250,height=200,status=0",true)
obj=$winP.document
obj.write('<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">')
obj.write('<html><head><title>Calendar</title>\n');
obj.write('<style type=\'text\/css\'>\n')
obj.write('table {width:100%;border-width: 3px;border-style:solid;border-spacing:0;border-collapse:collapse;}\n')
obj.write('td,th {font-size:12px;margin:0px;border-width: 2px 2px 2px 2px;border-style:solid;border-spacing:0;border-collapse:collapse;text-align:center;cursor:hand}\n')
obj.write('td:hover {background-color:yellow;font-weight:bold;cursor:pointer}\n')
obj.write('.hv:hover {background-color:yellow;font-weight:bold;cursor:pointer}\n')
obj.write('.igray {background-color:#BDBDBD}\n')
obj.write('.iwhite {background-color:white}\n')
obj.write('p {width:100%;text-align:center;margin:0}\n')
obj.write('<\/style>\n')
obj.write('</head><body>');
obj.write('<table>');
obj.write('<tr><th class=\'hv\' onclick=window.opener.$cP(\"'+myid+'\",\"'+query2+'\",\"'+ldm+'\")>&lt;</th><th colspan=5>'+months[curdate.getMonth()]+" "+ curdate.getFullYear()+'</th><th class=\'hv\' onclick=window.opener.$cP(\"'+myid+'\",\"'+query2+'\",\"'+ndm+'\")>&gt;</th></tr>')
obj.write('<tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>')
var myhtml=""
fdm.setDate(fdm.getDate()+1)
for (x=1;x<=5;x++){
myhtml +="<tr>"
for(y=1;y<=7;y++){
newmth=fdm.getMonth()+1
newyr=fdm.getFullYear()
if (curmth != newmth || curyr != newyr)
cal='igray'
else
cal='iwhite'
switch (query2){
case "MDY":
sdm=(fdm.getMonth()+1)+"/"+fdm.getDate()+"/"+fdm.getFullYear()
break
case "DMY":
sdm=fdm.getDate()+"/"+(fdm.getMonth()+1)+"/"+fdm.getFullYear()
break
default:
sdm=fdm.getFullYear()+"-"+(fdm.getMonth()+1)+"-"+fdm.getDate()
}
myhtml +="<td class='"+cal+"' onclick='window.opener.document.getElementById(\""+myid+"\").value=\""+sdm+"\";self.close()'>"+fdm.getDate()+"</td>\n"
fdm.setDate(fdm.getDate()+1)
}
myhtml +="</tr>"
if (x==5 && fdm.getDate() > 29)
x -=1
}
obj.write(myhtml)
obj.write('</table>');
obj.write('<p><a href="javascript:self.close()">close</a></p>');
obj.write('</body></html>');
obj.close();
obj.focus();

}

There is no preset available. The function is complete by itself. Just call the function and pass the necessary parameter and that is all.

In your form you would set the date input field as below example

<input type="text" name="mydate" id="mydate" value="" readonly onclick="$cP(this.id,'YMD')">

When user clicks on the input, the calendar will popup for user to choose a date.

User can navigate by month to choose different months using the "<" and ">" on both sides of the month indicator.

The second parameter of the $cP function has three formats. "YMD" displays "YYYY-MM-DD" format. "DMY" displays "DD/MM/YYYY" format. Finally, "MDY" displays "MM/DD/YYYY" format.

I do not want to add more options beside the three that I always use. It is up to individuals to add their own options. Adding it is very simple. Just go to the place where the switch(query2) is and add another case option.

The above is tested on IE7. Although I could not make the size of the popup less than that which IE7 limited. It worked just fine. Even the css hover worked after I set the DTD to "strict".

On Firefox, the window features seems to have a mind of its own. It does not allow me to hide a number of features which I turned off. However, this is firefox's preferred setting and since it does not hamper the functionality, it is acceptable despite having a bit too much unnecessary things.

On Chrome, only the address line is still visible.

I did not have other browsers installed thus does not test those.


Monday, December 13, 2010

Form Validation update

Previous post on the same subject saw a list of functions. Below is a modified update.

var errMsg="";
var $vF= function(qtype,query,query2,startw,endw){
//use $vF() without param to echo errMsg and clears it for the next form validation.
var tempMsg="";
var varRegEx=/.+/;
var testvalue="";
if (startw==null)
startw=""
if (endw==null)
endw=""
var regExAry={
"Empty":" must not be empty\n",
"SqlOK":" must not be empty or contains tab, enter, quotation marks, ampersand or semicolon character\n",
"Email":" is not valid Email\n",
"URL":" is not valid URL\n",
"Number":" is not valid Number\n",
"Alpha":" must not be empty and is Alphabet and space only\n",
"Integer":" is not valid Integer\n",
"Range":" is not between " +startw+ " and "+ endw+"\n",
"Zip":" is not valid Post Code\n",
"Positive":" is not positive number\n",
"Begin":" must start with "+startw+" and is "+endw+" digits\n",
"Date":" is not valid Date (DMY, MDY, or YMD)\n",
"YMD":" is not valid Date (DMY, MDY, or YMD)\n",
"Phone":" is not a valid phone number\n",
"Pwd":" must start with an Alphabet followed by at least one each of upper case, lower case, number and special characters. Length must be "+startw + " to "+endw+" characters\n",
"Radio":" must have a selecstion\n",
"Select": " must have a selection\n",
"CheckBox":" must be checked\n",
"CheckBoxList":" must have at least one item checked\n",
"AgteB":" must be greater than or equal "+endw+"\n",
"AeqB":" must be same as "+endw+"\n",
"Fixed":" must be exactly "+startw+" characters\n",
"Maxlen":" must not exceed "+startw+" characters\n",
"Name":" must be proper name with caps on every first character of word\n"
}
if (qtype!="Radio" && qtype !="Select" && typeof(qtype) != "undefined")
testvalue=query.value
switch (qtype){
case "Empty":
varRegEx=/.+/
break
case "SqlOK":
if (query.nodeName != "TEXTAREA")
varRegEx=/[\0\f\n\r\t\v'"&;]/
else
varRegEx=/[\0'"&;]/
break
case "Email":
varRegEx = /^([a-z0-9]+)([_\-.][a-z0-9]+)*@+([a-z0-9]+)([_\-.][a-z0-9]+)*[.]+[a-z]{2,4}$/i;
break
case "URL":
varRegEx = /^(HTTPS?|FTP):\/\/[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,4}(\/.+)*\/?$/i;
break
case "Alpha":
varRegEx = /(^[a-z ]+$)/i;
break
case "Number":
varRegEx = /(^[+-]?[0-9]+\.[0-9]{1,}$)|(^[+-]?[0-9]+$)/;
break
case "Integer":
varRegEx = /^[+-]?[0-9]+$/;
break
case "Range":
var locRegEx = /^[0-9]+$/;
var localtest=locRegEx.test(testvalue)
if (localtest){
testvalue=testvalue*1
if (testvalue < startw || testvalue > endw)
testvalue=""
}
else
testvalue="true"
break
case "AgteB":
// B is actually less than A so no need a "Less Than" test.
var locRegEx = /^[0-9]+$/;
var swv=startw.value*1
var localtest=locRegEx.test(testvalue)
if (localtest){
testvalue=testvalue*1
if (testvalue < swv)
testvalue=""
}
else
testvalue="true"
break
case "AeqB":
if (testvalue != startw.value)
testvalue=""
break
case "Zip":
varRegEx = /^[0-9]{6}$/;
break
case "Fixed":
varRegEx = new RegExp("^(.|\n){"+startw+"}$")
break
case "Maxlen":
varRegEx = new RegExp("^(.|\n){1,"+startw+"}$")
break
case "Positive":
varRegEx = /(^[+]?[0-9]+\.[0-9]+$)|(^[+]?[0-9]+$)/;
break
case "Begin":
startw +=""
var myrlen=endw-startw.length
startw = startw.replace(/\\/g,"\\\\")
startw = startw.replace(/\//g,"\/")
startw = startw.replace(/\-/g,"\-")
varRegEx = new RegExp("(^"+startw+"[0-9]{"+myrlen+"}$)","");
break
case "Date":
varRegEx = /^((0?[1-9]|1[0-2])[\/-](0?[1-9]|(1[0-9]|2[0-9])|3[01])[\/-][12][0-9]{3})|((0?[1-9]|[12][0-9]|3[01])[\/-](0?[1-9]|1[0-2])[\/-][12][0-9]{3})|([12][0-9]{3}[\/-](0?[1-9]|1[0-2])[\/-](0?[1-9]|[12][0-9]|3[01]))$/;
break
case "YMD":
varRegEx = /^[12][0-9]{3}[\/-](0?[1-9]|1[0-2])[\/-](0?[1-9]|[12][0-9]|3[01])$/;
break
case "Phone":
varRegEx = /^(\+?65)?[689]{1}[0-9]{7}$/
break
case "Pwd":
varRegEx = new RegExp("(?=^.{"+startw+","+endw+"}$)[a-zA-Z]+(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[^a-zA-Z0-9])")
break
case "Name":
varRegEx = /^[A-Z][a-z]+( [A-Z][a-z.]+)*( [A-Z]+)*$/
break
case "Radio":
for (radb=0;radb<query.length;radb++){
if (query[radb].checked == true)
testvalue="true"
}
break
case "Select":
if (query.selectedIndex != 0)
testvalue="true"
break
case "CheckBox":
if (query.checked == false)
testvalue=""
break
case "CheckBox":
if (query.checked == false)
testvalue=""
break
case "CheckBoxList":
var qform=query.form
var x
var qcnt=0
for (x=0;x<qform.elements.length;x++){
if (qform.elements[x].name == query.name){
if(qform.elements[x].checked == true)
qcnt=1
}
}
if (qcnt==0)
testvalue=""
break
default:
if(errMsg !="")
alert(errMsg)
errMsg=""
return 0
}
if ((varRegEx.test(testvalue)== false && qtype !="SqlOK") ||(qtype=="SqlOK" && varRegEx.test(testvalue)==true))
errMsg +=query2+regExAry[qtype]
return 0
};

The use of the above is quite straightforward. There is no setting required. Just perform the validation straight away. There is only a caveat that you should be aware of . The errMsg string will keep concatenating every time you run the function until you run the function without parameters.

Basically you should do the following.

obj=document,formname
$vF("Empty",obj.StartDate,"Registration Date")
$vF("Email",obj.Email,"Email")
$vF()

The function has 3-5 parameters. Most of the functions only uses 3. Javascript can accept null input parameters. The first parameter tells the function what test you are performing on the next parameter which is the form input element name to be tested. The third parameter is the user friendly name for the input element.

Fourth and fifth parameter is used for start/stop, max/min number for range test. It is also used to define a second input element name and its friendly name respectively. Some of the fourth parameter contains a number and there is no fifth parameter. This is usually used for testing for a fixed length of input.

You need not perform the test only once per input element. More test can be performed on the same input. For example, you perform a test on an input to ensure that it is a integer number and then perform another test on the same element to ensure that the number is exactly 6 digits.

At times you may want to perform condtional validation test. That is to say the input may not have entry but if it has an entry then the validation is performed, then you have to enclose the function with a condition test to ensure that the validation is bypassed if there is no input. The reason being all validation requires input to have a value (except the empty test).

$vF() will output the failed validation messages. At the same time it clears the errMsg content so that you could perform new set of tests.


Friday, December 10, 2010

Validating checkbox with same name

Normally validating checkbox with the same name is pretty simple. However, to submit to PHP you would want to use the name like xx[]. This then posts a problem in form validation as we cannot use document.form.xx[][1].checked to check if the element is checked.

It turned out that it is quite simple. Just treat the name as name and use the method below

document.form["xx[]"][1].checked


Wednesday, December 08, 2010

Javascript Regex

The following regex is valid.

myreg=/\w{2,3}/

However, if you use it to test "abcd", it still return true unless you test it with "a".

It turns out that you must code it as

myreg=/^\w{2,3}$/

just to get it return the right answer.

I have a headache with "^" and "$". I really don't know whether to use it or not. It seems like not every regex I used have to include them.

The trick is try without them first. If fail, then adds them in.

Thursday, December 02, 2010

Creating Regex with literal backslash

Backslash in Regex has special meanings. So how do I create a Regex expression that contains a literal backslash.

It is quite simple. Just use "\\" instead of "\" in the Regex.

Now come the problem. I need to define a string variable and pass it to a function to create a Regex in the function.

For example, I need to create a string "A\" . The string can be defined as myvar="A\\" in javascript. Up till now it is fine. Now if I set

myRegex=new RegExp("^"+myvar,"")

in the function and test it, the script crashes.

It turned out that I must define the string as myvar="A\\\\" so that the RegExp can see the string as "A\\" and parse it as a literal "A\".

So much trouble to just create a backslash in Regex.

Wednesday, December 01, 2010

Javascript Regex with numbers

Javascript Regex is a powerful tool. However, there is something you must take note when doing validation with numbers.

if your regex is /[0-9]+/ and your intention is to ensure that the input is just numbers. You would be surprised that when you enter ".1" or "1." it still passes.

I am not sure what happened but isNaN also behaves this way.

To ensure that only numbers is valid you would have to set the regex as /^[0-9]+$/

Tuesday, November 23, 2010

Getting element from DOM tree

If we want to get a cell element from a table, we would get the id of the table first. With the ID then we will navigate through the rows and cols to get to the cell.

A simple way to get this is

mycell = tblid.childNodes[x].childNodes[w]

Unfortunately, it is not that simple. Usually when people write html, they tends to spread out the tags in different lines for easier visibility. Often you would do this

<tr>
<td>text<td>
<tr>

In IE you would not have a problem as IE would ignore the whitespaces. However, other browsers are more specific. They will not ignore the whitespaces.

If you use the same simple code, you will not get the element that you wanted. You would have to find a way to ignore the whitespaces like IE.

The following is a simple code to do it.

function getcell(tbdid,params){
var z;
var zz;
addEval=tbdid
for (y=0;y<params.length;y++){
zz=-1
for (z=0;z<params[y];z++){
if (addEval.childNodes[z].nodeType != 1)
zz +=1
zz+=1
}
addEval=addEval.childNodes[zz]
}
return addEval
}
mycell=getcell(tblid,[x,w])

Note that x and w are numbers starting with 1 instead of 0.

Monday, November 22, 2010

Close top window automatically without prompt

In IE6 I used to do this

window.opener="x"
window.close()

The window will close nicely without prompting.

In IE7 it will not work. Instead use the following

window.open('','_self','');
window.close()

Wednesday, November 17, 2010

SetTimeout to temporarily disable buttons

Normally you would call the function and pass a callback function name to it so that at the time out event your function will be called.

Now what if I want to use the same call back function to act on different DOM elements? For example, I want to disable the button for a few seconds when I click on it. The disabling is to prevent user from clicking on it multiple times. The problem is that there are a few buttons of similar nature that acts differently on clicking. Instead of having to create different callback functions for each button, I want to use the same function for all the buttons.

It turned out that this could be done.

In your INPUT create a "onclick" event by calling a function and pass "this" as parameter.

In the called function do the following

myattribute=document.createAttribute("disabled")
myattribute.nodeValue=true
param.setAttributeNode(myattribute)
settimeout(function(){mycallback(param)},1000)

The first three lines will disable the button. The fourth line will call the timeout with mycallback as function. It is actually a dynamic function that calls mycallback function by passing the INPUT object as parameter. This means that the script still creates different functions for each button but it will not be created till user clicks on it. Coding wise this is easier to maintain than you create all the functions manually.

mycallback will then be able to act on the "param" (which is the "INPUT" object) by calling

param.removeAttribute("disabled")


Friday, October 15, 2010

Dollar Sign function in JS

I have seen function like $("myid") in a number of javascript libraries. It worked fine for most browsers. JQuery, Prototype etc all uses this type of function name or name prefixed with $ sign. By itself it is no big deal. However, you cannot mix different libraries that uses functions that has $ signs or function names that prefixed with $. Inevitably, you may come across with functions with the same names across different libraries.

The following is a basic example of the use of $ function.

function $(idname){
return document.getElementById(idname)
}

var mytext=$("myid").innerHTML

Many Javascript Libraries have much more elaborate functionalities using this type function name.

Monday, October 04, 2010

Javascript associative array testing

Try the following to see if it worked.

myary=new Array();
myary["xx"]=1
if ( myary == "")
alert("myary is null/undefined/nothing")
if (typeof myary =="object")
alert("is obj")

It returns two alerts. But it is not correct as myary did have a value.

change myary["xx"]=1 to myary[0]=1

You will get only the second alert.

try the original script but this time change if(myary == "") to if(myary === "")

again only the second alert is shown.

Checking an array to see if it is empty is kind of awkward. It is not null or "undefined" as you already defined it as array.

Depending on the type of array, the results may be different between using "== " and "===" to compare with "" (empty).

1. If there is no value defined, "==" returns "true" whereas "===" return "false" and the length returned is 0.

2. If there is a valued defined (normal array), both test shows "false". The length returned one or greater.

3. if there is a value defined for associative array, "==" returns "true" whereas "==="return" false. The length returned is always 0.

As you can see, "===" always return false regardless of whether the array has a value. Using this to test whether the array is empty will not be fruitful.

On the other hand "==" actually returns "true" for associative arrays if it has a value. But then if the array has no value, "==" also returns "true".

The only sure way that I know is to use the following method to test

mytruefalse=false
for(x in myary){
mytruefalse=true
break
}

Friday, September 17, 2010

Dynamic add style to element

Previously I have problem setting the styles of elements from Javascript. I end up changing the className of the element to achieve the desired effect. Recently, I saw from some one's blog saying that using the following method can actually change element style dynamically.

document.getElementById("myid").style.cssText="font-size:20px;font-weight:bold;"

This method works for both IE (tested in IE6,IE7) and Firefox (ver 3.6).

Note that you actually replaces the old style with your new style using this method.

To add style to existing styles do this

document.getElementById("myid").style.cssText +="color:red"

I noticed that IE7 does not add new style element to the existing style if you don't prepend a ";"

Note that it still replaces the old style if the added element already exists.

Wednesday, September 15, 2010

Dynamic add elements with a twist

I used to create tables and add rows and columns dynamically to it using javascript. At other times, I also need to remove all elements from a select tag and add a custom list of options to it.

It is quite tedious to add elements manually. Thus, I thought why not add it using functions.

On trying, I noticed that basically I need a element id to add the elements for both types of requirement. Then, it comes to my mind to try new ways of doing it using classes. Furthermore, I would not want to repeat the part where I get the id of the element.

Thus, I created a "class" which has a nested class in it so that I could use syntax like

addElements("id").addtd(myarray)

Well, the syntax looks funny but it actually works. I use "closures" to achieve this. The code is as belows.

/*
General Syntax - AddElements("yourid").functionname(params)
params :-
1. array - a list of items defined by an array e.g. ["a","b","c","d","e"]
2. element,assocarray - and element and an assocarray e.g "span",{'class':'myclass','id':'myid'}
3. text - any text appropriate for the docid property involved
For the assocarray, it is a good practice to use single quotes even for the keys. If no property required then use "" instead.
Available functions:-
addtd(array) - add a table row pair ("TR") with TD populated by the items in the array
replOpt(array) - remove all the <select> options and populate the options from the array.
addE(element,assocarray) - add the element and set the property populated by the items in assocarray. See params 2 above
addStyle(text) -adds a style to the docid itself. e.g. "font-weight:bold;font-size:30px"
replStyle(text) -replaces a style to the docid itself. e.g. "color:red"
addText(text) - similar to addStyle but add the text into the textnode of the element involved.
replText(text) - similar to addText but replaces the content of the textnode of the element
*/
var addElements = function(docref) {
tbdid=document.getElementById(docref)
var addDomE = {
addtd: function(nodearray){
trid=document.createElement("tr");
for (ndtxt=0;ndtxt<>
tdid=document.createElement("td")
txtid=document.createTextNode(nodearray[ndtxt])
tdid.appendChild(txtid)
trid.appendChild(tdid)
tbdid.appendChild(trid)
}
},
replOpt: function(nodearray){
for (ndtxt=tbdid.length-1;ndtxt>-1;ndtxt--){
tbdid.remove(ndtxt)
}
selnid=document.createElement("option")
selnid.value=""
selnid.text="Please select"
selnid.selected=true
if(navigator.appName =="Microsoft Internet Explorer")
tbdid.add(selnid)
else
tbdid.appendChild(selnid)
for (ndtxt=0;ndtxt<>
selnid=document.createElement("option")
selnid.text=nodearray[ndtxt]
selnid.value=nodearray[ndtxt]
if(navigator.appName =="Microsoft Internet Explorer")
tbdid.add(selnid)
else
tbdid.appendChild(selnid)
}
},
addE: function (htmltag,params){
myelement=document.createElement(htmltag)
if (params != ""){
for (addEval in params){
if (addEval!="html"){
myattribute=document.createAttribute(addEval)
myattribute.nodeValue=params[addEval]
myelement.setAttributeNode(myattribute)
} else {
mytxtnode=document.createTextNode(params[addEval])
myelement.appendChild(mytxtnode)
}
}
}
tbdid.appendChild(myelement)
},
addStyle: function(params){
params = ";"+params
tbdid.style.cssText +=params
},
replStyle: function(params){
tbdid.style.cssText = params
},
addText: function(params){
mytxtnode=document.createTextNode(params)
tbdid.appendChild(mytxtnode)
},
replText: function(params){
mytxtnode=document.createTextNode(params)
mynodes=tbdid.childNodes
while (tbdid.hasChildNodes()){
tbdid.removeChild(tbdid.lastChild)
}
tbdid.appendChild(mytxtnode)
}
}
return addDomE;
}
;

In the HTML side you have to first setup one tbody element (not table element) with id to add td elements . For select element, you just use the select id.

Next , you create an array of td element or option element. Finally just use one of the following to do the trick

addElements("myid").addtd(myary);
addElements("selid").replOpt(myary);

addtd is for adding td elements. replOpt is for options element.

Monday, August 23, 2010

Ajax XMLHttpRequest object in IE

It is quite hateful using XMLHttpRequest across browsers. This is especially severe in the case of IE.

In IE7 and above or other browsers you have to use the standard

obj = new XMLHttpRequest();

In IE6 or below, depending on versions of MSXML installed, you will have to use

obj = new ActiveXObject("Msxml2.XMLHTTP");

or

obj = new ActiveXObject("Microsoft.XMLHTTP");




Dynamic add option to Select Element

//first clear the content
obj=document.getElementByID("mysel")
mysize=obj.length
for (x=mysize-1;x>-1;x--){
obj.remove(x)
}
myobj=document.createElement("option")
myobj.text=myary[x]
myobj.value=myary[x]
myobj.selected =true
if (navigator.appName=="Microsoft Internet Explorer")
obj.add(myobj)
else
obj.appendChild(myobj)

Wednesday, August 11, 2010

Javascript Pivot

Creating pivots in HTML like that of Excel is very much harder. It take a bit of understanding of Javascript to do it. The following is a lazy way of showing a pivot

Save the following as pivottable. js file.

pivotTable =function (){
//first include this class
// create a new class var xx=new pivotTable()
//pass a tbody id to tblID as xx.tbID="idtext"
//add rows by calling xx.insertRaw tblindex is row value, thlPivot is pivot col and tblPivotValue is the numeric value of the pivot col
//finally call showTable as xx.showTable()
this.pivotList="";
this.tblID="";
this.pivotArray=new Array();
this.indexArray=new Array();
this.mainArray=new Array();
this.totalArray=new Array();
}
pivotTable.prototype = {
insertRaw : function(tblIndex,tblPivot,tblPivotValue){
if (typeof this.indexArray[tblIndex] =="undefined")
this.indexArray[tblIndex]=tblIndex;
if (typeof this.pivotArray[tblPivot] =="undefined")
this.pivotArray[tblPivot]=tblPivot;
if (typeof this.mainArray[tblIndex] == "undefined")
this.mainArray[tblIndex]=new Array();
if (typeof this.mainArray[tblIndex][tblPivot] =="undefined")
this.mainArray[tblIndex][tblPivot]=tblPivotValue;
else
this.mainArray[tblIndex][tblPivot]=this.mainArray[tblIndex][tblPivot]+tblPivotValue;
if (typeof this.totalArray[tblPivot] =="undefined")
this.totalArray[tblPivot]=tblPivotValue;
else
this.totalArray[tblPivot]=this.totalArray[tblPivot]+tblPivotValue;
},
showTable : function(){
myid=document.getElementById(this.tblID)
mytr=document.createElement("tr");
myth=document.createElement("th");
mytext=document.createTextNode("\u00a0")
myth.appendChild(mytext)
mytr.appendChild(myth)
for(myindex in this.pivotArray){
myth=document.createElement("th");
mytext=document.createTextNode(myindex)
myth.appendChild(mytext)
mytr.appendChild(myth)
}
myid.appendChild(mytr);
for (myx in this.indexArray){
mytr=document.createElement("tr");
mytd=document.createElement("th")
mytext=document.createTextNode(myx)
mytd.appendChild(mytext)
mytr.appendChild(mytd)
for (myy in this.pivotArray){
mytd=document.createElement("td");
if (typeof this.mainArray[myx][myy] == "undefined")
mytext=document.createTextNode("0");
else
mytext=document.createTextNode(this.mainArray[myx][myy]);
mytd.appendChild(mytext);
mytr.appendChild(mytd);
}
myid.appendChild(mytr);
}
mytr=document.createElement("tr");
mytd=document.createElement("th")
mytext=document.createTextNode("Total")
mytd.appendChild(mytext)
mytr.appendChild(mytd)
for(myp in this.pivotArray){
mytd=document.createElement("td")
mytext=document.createTextNode(this.totalArray[myp])
mytd.appendChild(mytext)
mytr.appendChild(mytd)
}
myid.appendChild(mytr)
}
}

Include the pivottable.js and the following in your web page.

mypivot=new pivotTable();
mypivot.tblID="mydiv";
mypivot.insertRaw("firstrow","Acol",1)
mypivot.insertRaw("secondrow","Acol",1)
mypivot.insertRaw("secondrow","Bcol",1)
mypivot.insertRaw("secondrow","Ccol",1)
mypivot.insertRaw("thirdrow","Dcol",5)
mypivot.showTable();

Create a table with a tbody. The tbody id is "mydiv". You will see a 4x4 table displayed.

Tuesday, August 10, 2010

Javascript Class

I have been writing Javascript codes for a long time. Although there is this "class" thing in Javascript, I have never come close to need to use it. However, recent coding requirements forced me to look at it closer.

There is a web page that needs to mark a check box list upon selecting a product from a drop down list. Each product has a specific list of items that need to be checked. Normally I would retrieve all the products and their items and make them into an associative array. When user selects a product the items tagged with the product will then populate the checkbox accordingly.

However, the products are duplicated with different plans. This means that I have to have a multi-dimension arrays. Now, if the data is huge, then my web page loading will be slow. So I though why not use "Ajax" technology to retrieve only the particular checkbox list. As it goes, everything goes smoothly with a slight delay as the data need to be retrieved across the network.

When the next request to amend the web page with the ability to check for duplicate product entry, I was thinking of not submitting the form then check for duplicates as I need to fill the form with user's submitted content should duplicates occur. Thus, the best choice is to just check for duplicates using "Ajax". I am faced with having to double coding of the same "Ajax" script. The script is tailored to a single process and is not adaptive to another process.

Since the basic codes are generic and only certain parameters like URL and Callback functions need to be specific, I though why not create an "Ajax" class to create instances of the Ajax codes so that I could use a single code with different callbacks to do the job. After all, only the URL and callbacks are process specific.

Thus, I began the learning of the "class" in Javascript. As it turn out, Javascript don't actually have "class". It only have "objects". However, the object behaves quite similar to "class". The "class" constructor is actually an "object" constructor. Basically the "class" is a "function" object.

function mySpecie(){

}

You create and instance of the function by

myInstane = new mySpecie();

Well, normally you will never need to create instances of the function since I could call the function and just pass parameters to it. However, there is always a need to set certain parameters that does not change. For example, I need to store particulars of a group of species. Instead of having to define that they are humans one by one, I could have set globally that the species is "human" then I can concentrate on the particulars that are specific to the species. Now simple functions can't store parameters. It has to be passed as parameters every time.

There is a way to set certain paramaters as fixed values in the function. This is done by the keyword "this".

function mySpecie(){
this.specie="human"
this.name="Jon";
this.sex="male";
}

In this way, you don't have to set the name and sex every time you call the function. Nice huh! What if I need to add/change ad hoc information during the running of the program? A "Class" has this ability to do it right? Javascript has this thing called "prototype" in functions. You could add or change any values to the function at anytime and it will remember the values when you call the function. You can set the values by

mySpecie.prototype.specieType = "notHuman"

So whenever you call the instance of mySpecie, you get to have the setting of specieType as "notHuman" instead.

In other words, you could set and change the parameters as and when you like.

As it goes, "class" can have functions. Well, Javascript can also have function in functions.

function mySpecie(){
this.name="Jon"
this.hello = function(){
echo (this.name)
}
}
myInstanc=new mySpecie();

When you set "myInstance.hello()", you get the reply as "Jon".

I also learn that you can set multiple parameter values without having to keep defining "prototype".

mySpecie.prototype = {
name : "Jon",
hello : function (){
echo (this.name)
}
}

One other thing I learn is that I could create a function and pass this function as part of the class.

function hello{
echo "Hi";
}
myInstace.prototype.hello = hello

Actually I could easily pass the function as a function parameter into the instance on the run. All I need to do is to set the instance's value "var hello=hello".

myInstance("xml.php",hello);

With the above methods, I could pass the function into the instance and use it as part of the class.

It is certainly easy now to use multiple instances of "Ajax". I could create the class and then set the URL and callback accordingly and still use one set of code. All I need to do is pass the parameters to the instances of "Ajax" class.