I have been trying a few through the past years, no deep-diving but rather using what I need for the moment.
The very first time I needed Ajax I created my own functionality with the help from some tutorials on developerWorks. After that I started with Dojo for simple Ajax calls which made life much easier. Then I moved on and tried Ext.js also for Ajax calls but also using its json object. I have briefly looked at Prototype and Rico and now latest I have gotten into jQuery, I really like its simplicity and variety.
But I am curious in how other people/developers reason. Here are the JavaScript frameworks that I know of and found when browsing for a while. What's your opinion and why? Any other options?
For a specific task I needed the functionality that you can see on the Google search box. And by that I mean that as letters are typed into the search box, the results are displayed in a dynamic box below. Further on I can whenever I choose to, press the arrow down key to start navigating over the result list. And when pressing enter the specific row that is highlighted is chosen.
If you start trying this yourself you'll find out that you probably need to do some magic with CSS and JavaScript to make it work like this. I am sure this is fun work but would take some time if you decide to implement it completely on your own.
A simpler and very easy and fast way to get it done is to use a solution ready for use and there is a plugin for JQuery that does exactly this. Here are five steps to get it done (with dummy data).
1. Download JQuery 2. Download the JQuery Autocomplete plugin 3. Include the JavaScript libraries on your web page 4. Add an input field 5. Add three JavaScript rows
<script type="text/javascript"> $(document).ready(function(){ var data = "blue green white red yellow black pink purple brown orange".split(" "); $("#myInput").autocomplete(data); }); </script>
A way to move on with this would for example be to instead of using the dummy string as above, to create a string/array with all search data when the pages loades using ajax to a background database.
<table border="1" cellpadding="4" cellspacing="0"><tr onMouseOver="this.style.backgroundColor='#E0E0E0';" onMouseOut="this.style.backgroundColor='#FFFFFF'" style="cursor:Pointer"><td>Row value 1</td><td>Row value 2</td><td>Row value 3</td></tr><tr onMouseOver="this.style.backgroundColor='#E0E0E0';" onMouseOut="this.style.backgroundColor='#FFFFFF'" style="cursor:Pointer"><td>Row value 1</td><td>Row value 2</td><td>Row value 3</td></tr><tr onMouseOver="this.style.backgroundColor='#E0E0E0';" onMouseOut="this.style.backgroundColor='#FFFFFF'" style="cursor:Pointer"><td>Row value 1</td><td>Row value 2</td><td>Row value 3</td></tr></table>
Row hovering with different colors:
Row value 1
Row value 2
Row value 3
Row value 1
Row value 2
Row value 3
Row value 1
Row value 2
Row value 3
Code:
<table border="1" cellpadding="4" cellspacing="0"><tr onMouseOver="this.style.backgroundColor='#FF0000';" onMouseOut="this.style.backgroundColor='#FFFFFF'" style="cursor:Pointer"><td>Row value 1</td><td>Row value 2</td><td>Row value 3</td></tr><tr onMouseOver="this.style.backgroundColor='#00FF00';" onMouseOut="this.style.backgroundColor='#FFFFFF'" style="cursor:Pointer"><td>Row value 1</td><td>Row value 2</td><td>Row value 3</td></tr><tr onMouseOver="this.style.backgroundColor='#0000FF';" onMouseOut="this.style.backgroundColor='#FFFFFF'" style="cursor:Pointer"><td>Row value 1</td><td>Row value 2</td><td>Row value 3</td></tr></table>
I recently blogged about how to display a text as columns with PHP. Now, thanks to PHP.JS, which I have also blogged about, I have ported the same functionality to JavaScript.
No work from my side really other than using the corresponding PHP functions from PHP.JS and creating my own JavaScript split_pos function. I have also created a print_columns function that calls split_pos and renders the columns on the web page. Currently, as you can see, this function is pretty hard-coded and can only handle one and two columns. I will update this entry with a more abstract version if I get the time to do so.
You need to download and include the package from PHP.JS for this to work since several ported JavaScript functions from this library are being used.
function split_pos(text) { var mid; var cut; var part1; var pos1; var pos2; var pos3;
/* find middle space in text */ mid = strlen(text)/2 - 1; cut = strpos(text , ' ' , mid); part1= substr(text , 0 , cut + 1);
Sometimes it happens to me that I really would like to use a PHP function in JavaScript. Instead of making unnecessary AJAX calls to accomplish this it would be nice if you could use the same functionality in JavaScript.
Now, this happens to be possible in an easy way thanks to PHP.JS, which is an open source project in which PHP functions are ported to JavaScript functions.
To use PHP.JS you just download it (for free), include it and call the functions. Very easy and useful.
Developer Kevin van Zonneveld started this when working on a project and decided to keep on working on it afterwards with the goal to provide a php.js file available as open source.
JSLint is a JavaScript code quality tool which you can use for free to validate your JavaScript.
JavaScript is not a very strict language but in some cases you might bump into situations when you need to find an error which is caused by another and so on and therefore hard to find. In these cases this tool will be of great use to you. As you can see on their homepage there are many extra options to choose from as well regarding the validation.
I pasted one of my script libraries in here and found several smaller errors. I think it's about time to get rid of them now.
I have pasted a small function below with some intentional errors in it just to demonstrate the feedback you might get back.
function validateFields(fldName,labelName,validation) { var str = ""; var iChar = ""; var orgStr = "";
if (validation == "isEmptyString") { if (document.getElementById(fldName).value == "") { str = str + "Field '" + labelName + "' must have a value!\n"; } } else if (validation == "isNumber") { if (!isNumber(document.getElementById(fldName).value)) { str = str + "Field '" + labelName + "' is not a number!\n"; } } else if (validation == "specialChars") { orgStr = document.getElementById(fldName).value;
var char1Pos = orgStr.indexOf('"'); var char2Pos = orgStr.indexOf('\\');
if (char1Pos >= 0) { str = str + "The character " + orgStr.charAt(char1Pos) + " is not allowed for field '" + labelName + "'\n"; } else if (char2Pos >= 0) { str = str + "The character " + orgStr.charAt(char2Pos) + " is not allowed for field '" + labelName + "'\n"; } }
For a web administration interface that we have developed here on Wohill we are currently using Ext JS for the AJAX functionality when saving and getting information from the database back and forth to the interface. We are using TinyMCE as the text editor when creating some kind of content to get a more desktop feeling.
When receiving information for a page which contains name, title, image, date and text, an asynchronous request is sent in the backround to get the data from the database. When the data has been queried from the database and we have a resultset, I am building a small JSON object with this information which is then sent back to the admin interface.
When receiving this information on the client (admin interface) side we need to decode the json object to be able to use all the pieces of information separately.
This workflow works fine in Firefox and Google Chrome but for Internet Explorer 7 (which is the only version of IE I have tested it on) it doesn't. The problem is when the text body (which is html) contains line break carrige return. Invincible characters in the string like '\r' and '\n' is what causes the error "Unterminated String Constant".
The JSON object that is built before sent to the client looks something like this:
var obj = Ext.decode(respStr); alert(obj.header); alert(obj.subHeader); // etc.
To make the fix for the error message in Internet Explorer; work with the response string a bit before decoding it and you will get rid of the error message. What happens is that all line break carrige returns are escaped:
var re = /\n/g; respStr = respStr.replace(re, '\\n'); re = /\r/g; respStr = respStr.replace(re, '\\r');
var obj = Ext.decode(respStr); alert(obj.header); alert(obj.subHeader); // etc.
Here is some more info on this problem. But in this case they had problem with IE 8 and not 7.
I downloaded the rather new Ext Core 3.0, both the development and the production packages. It was very easy to "install" and start using it. However when I tried to do some simple ajax (getting data asynchronously from another page in this case) I got an error message.
This code is used to send form data to a back-end page.
<script src="js/ext-core-debug.js"></script>
<script type="text/javascript"> function controller_call() { Ext.Ajax.request({ url: 'controller/test.php', form: 'myForm', success: function(response, opts) { var obj = Ext.decode(response.responseText); console.dir(obj); console.log(response.responseText); }, failure: function(response, opts) { console.log('server-side failure with status code ' + response.status); } }); } </script>
When doing this the error message 'Ext.decode is not a function' is displayed.
Apparently this decode function (or actually the JSON functionality in general) is not by default included when including the javascript toolkit as desribed to do.
The way to fix this is to separately include the JSON package. Add this row to the above and it will work.
When you submit a form you need to validate your fields before continuing in order to know if the data is correct. One common way of doing so it is to validate them one by one which works fine but could be hard to read and takes up some space.
Another way is to first define the field names, their labels and type and then validate them all at the same type and get only one notification with all errors. Here's a little something I wrote that helps me out.
Above a form with four fields and a button. When clicked on I want the fields to validate, but they need to be validated on different things. The name and description field must not be an empty string, the age field must be a number and the Web field has to be an url.
First the function that defines the fields, their labels and their type and the call to the actual validation function. If the validation goes ok we move on with for example submitting the form. Else some notification according to the validation function.
function checkFieldsAndSubmit() { var fldArray = new Array(); var labelArray = new Array(); var valTypeArray = new Array();
if (validateFields(fldArray, labelArray, valTypeArray)) { alert("Submitting form..."); } }
The validation function. As you can see we can easily add another type of validation and how a specific field is suppose to validate:
function validateFields(fldArr, labelArr, valTypeArr) { var str = "";
for (i=0; i<fldarr.length; i++) {
if (valTypeArr[i] == "isEmptyString") { if (document.getElementById(fldArr[i]).value == "") { str = str + "Field '" + labelArr[i] + "' must have a value!\n"; } }
if (valTypeArr[i] == "isNumber") { if (!isNumber(document.getElementById(fldArr[i]).value)) { str = str + "Field '" + labelArr[i] + "' is not a number!\n"; } } if (valTypeArr[i] == "isUrl") { if (!isUrl(document.getElementById(fldArr[i]).value)) { str = str + "Field '" + labelArr[i] + "' is not a valid url!\n"; } } }
I posted a similar post some time ago now which was a Javascript function that was suppose to validate an url. It works ok but the function is very long and didn't cover all cases. For example the url must have "www" and the address can not start with "https".
So a much better way is to use a regular expression instead to match an input string with. If the function returns true the string is a valid url and else its not.
function urlCheck(str) { var v = new RegExp(); v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"); if (!v.test(str)) { return false; } return true; }
If you need more advanced/enhanced information when hovering a text on a webpage besides the usual yellow box with black text, there's a way to do it. You can change the background color, font color, add a border and have both text and images, in fact any html in the info box that comes up when hovering. Go away old alter text!
I found this functionality implemented on Planet Lotus. It is a solution developed by Walter Zorn and it is very easy to implement. See the instructions on this page on how to use the script.
In the meanwhile here's an example for you to look at.
In Lotus Notes we have the prompt, dialog box and input box to communicate with the user and get feedback or input. To display a message to the user the Messagebox is most often used in Lotusscript.
For displaying messages to users in JavaScript the alert function is something that everybody knows of that has worked with JavaScript. I have to admit that I didn't know of the very simple function to use when to get a yes or no from the user though - a confirmation. In case someone else also missed this here it is.
If you for example have a list of items displayed on a web page with a delete button on each row to which a delete function is tied to the button. Then if you click on the button the item is deleted. This can very easliy happen by mistake of course. So a little check would be in place before deleting in case you clicked on the button by mistake.
Use the confirm-function like this:
function delete() { var answer = confirm("Do you want to delete the selected item?");
One strange difference in my opinion between Firefox and Internet Explorer and most strange of all also a difference to Google Chrome is that the onclick-event is not recnognized. Here is a simple example just to illustrate.
This works fine in Firefox, i.e. the function 'getCategories' gets called when choosing an object in the select box. This does not work for the other browsers though, the calls are not made and there are even no errors raised.
The solution is to make the function call on the select-tag instead using the onchange-event referencing the value of the select tag (which will hold the value of the chosen option-tag),
When loading a page I have a Javascript function that gets information using AJAX. The function is used in the onload-event of the body tag to be executed when the page is loaded:
<body onload="getStuff();">
The getStuff function gets data from a backend controller page using AJAX and when the data is returned asynchronously a div is updated with the data. So what happens in the JavaScript function when data gets back is:
The problem is that sometimes (and this is to often to not care about it) the div don't get any content when the page is loaded. I am using Firebug so I can see that data is received via AJAX but it just isn't printed to the div. I tried to alert some text just to make sure that something was happening at this particular place in the code. And when I did, it suddenly displayed correctly.
If you have experienced this problem the explanation is that the div gets updated before it exist since the page is read from up to down. When you add an alert box it takes some extra milli seconds to execute and the div is defined and displayed before it gets updated with the ajax response.
But we don't want to have an alert there so what we do is make the function sleep just a little bit before we add the content to the div. This is accomplished using the setTimeout function. So replace the code in the onload-event of the body tag with this and it will start to work as expected:
<body onload="setTimeout('getStuff()', 500);">
Where 500 is 500 milliseconds. Sometimes it takes longer time to open a site and sometimes shorter. So try with some different numbers here and get some slack in case of possible low performance but still make it an acceptable time for the end user.
Here's a script that we are using to validate if an url has a proper format before submitting a form. In this function an empty url counts as valid, i.e. it is not mandatory. Someone else has written the script (don't know who) and I have made only small changes to it. Works ok for it's purpose though. You call this function from somewhere and if it returns true it is a valid url.
function isURL(urlStr) { if (urlStr.indexOf(" ") != -1) { alert("Spaces are not allowed in a URL"); return false; }
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]"; var validChars="\[^\\s" + specialChars + "\]"; var atom=validChars + '+'; var urlPat=/^http:\/\/(\w*)\.([\-\+a-z0-9]*)\.(\w*)/; var matchArray=urlStr.match(urlPat);
if (matchArray==null) { //alert("The URL seems incorrect \ncheck it begins with http://\n and it has 2 .'s"); return false; }
var user=matchArray[2]; var domain=matchArray[3];
for (i=0; i<user.length; i++) { if (user.charCodeAt(i)>127) { //alert("This domain contains invalid characters."); return false; } }
for (i=0; i<domain.length; i++) { if (domain.charCodeAt(i) > 127) { //alert("This domain name contains invalid characters."); return false; } }
var atomPat=new RegExp("^" + atom + "$"); var domArr=domain.split("."); var len=domArr.length;
for (i=0;i<len;i++) { if (domArr[i].search(atomPat) == -1) { //alert("The domain name does not seem to be valid."); return false; } }
return true; }
When discovering url's in the comments we're making use of regular expressions instead. That is, for every 'onkeyup' we're looking for the regular expression
When I wrote this simple script I wanted to use the modal window functionality for all browsers. When a modal window opens the focus is on it and it isn't possible to work with the calling page until you close the modal window. I couldn't find a way to accomplish this in Firefox so therefore the window opens up as a modal window in IE and as a regular window in FF.
/* Function for displaying a popup (modal) window */ function openWindow(url) { // If Internet explorer if (window.showModalDialog) { window.showModalDialog(url, 'Modal window', 'dialogWidth:500px;dialogHeight:770px;scroll:no'); } // If Mozilla else { window.open(url, 'Regular window', 'height=770,width=500,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes'); } }
It is also possible to get a return value from a modal window.
var myText = window.showModalDialog(...)
The modal window needs the following code to return a value and close the dialog
if (navigator.appName == "Microsoft Internet Explorer") { // Set return value window.returnValue = "Some text"; }
window.close();
If you are using a browser that can't handle modal windows you could call a function on the caller page from the modal window to get a return value and do something with it.
We received a comment lately from Dave asking for a specific scenario with the propercase function. The question was:
"Was wondering if it would be possible to modify the code so that one could highlight a word in a document, etc, and invoke the code with a right mouse click?"
We start by creating the scenario that we have a textarea in which you can type in text, highlight one or several words and then the propercase function will act upon these on a right mouse-button click.
First we need a textarea:
<html> <body> <textarea id="tArea">And here we have some predefined words that you can play with...</textarea> </body> </html>
And then we need some JavaScript to find out when a right mouse click occurs and to define what to do when that happens. The function that listens for the event looks like this. Note that it specifies the id of the textarea to watch for selected text and right mouse clicks. See Quirksmode for detailed explanation and examples on these events. This is the place where I got most of the code in this box.
document.onclick = actOnRightMouseClick;
function actOnRightMouseClick(e) { var rightclick; if (!e) var e = window.event; if (e.which) rightclick = (e.which == 3); else if (e.button) rightclick = (e.button == 2);
if (rightclick == true) { formatText(document.getElementById('tArea')); } }
When a right mouse click occurs we want something to happen on selected text and else nothing at all. The function above calls the function 'formatText'. This function catches the selected text, does something to it and places it back again formatted. The formatting in this function is making the selected text propercase, hence calling the propercase function.
/* Function for formatting selected text */ function formatText(el) { /* If Mozilla */ if (el.setSelectionRange) { var tmpStr = el.value.substring(el.selectionStart,el.selectionEnd); tmpStr = strProperCase(tmpStr); el.value = el.value.substring(0,el.selectionStart) + tmpStr + el.value.substring(el.selectionEnd,el.value.length) } /* If Microsoft Internet Explorer */ else { var selectedText = document.selection.createRange().text;
The propercase function looks like this and it is slightly different from the one presented in the earlier post.
function strProperCase(str) { var retVal = str.toLowerCase().replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); }); return retVal; }
Now it's time to try it out. Mark one or several words in the textarea below and click on the right mouse button and you will hopefully see the desired propercase effect. Voilà!
If you need to create random characters and/or numbers as a string for some reason - for example as a verification code for a comments function on a blog - here's a JavaScript that can help you.
/* Create a specified number of random characters and return it. Add numbers or other characters to the sourceArr the same way, if you want to extend it.
Example usage: createRandomNumber(6);
Output: "wohill"
@author Niklas Waller <nic[At]wohill.com> - www.wohill.com @version 2008-07-18 */ function createRandomNumber(varLength) { var sourceArr = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"); var randomKey; var randomCode = "";
In the new Wohill project - Stepcounter - we have a need to show some data for a specific month - a table with information for each day and a chart belonging to that data. When the page is loaded the table and chart is written to the page. The data is read from the backend using ajax. Why, you say? Well, users need to be able to move backward and forwards to the previous and next month. When this is done I need to use the same functionality to get the backend data but I don't want the page to reload each time. So all I really have to do is to use the same functionality but with different dates as an argument for the functions (or actually it is really string objects). To do this I need a date object that is created as a default date for the current year, month and day when the page is loaded for the first time. And then when clicking och previous or next the month part of the date should be incremented or decremented. I also need to handle begin date and end date for each month, since this is relevant for the backend functions.
// Global variable 'woDate' var woDate = new Date();
/** A month number that comes from the JavaScript date function 'getMonth()' spans from 0-11 where 0 is January. This function increments the month number so that it returns 1 instead for January. Calculate and return the month number of a date with a leading zero if the month number is less than 10 or else as is. */ function getMonthString(dte) { var retDate = ""; if (dte.getMonth()+1 < 10) { mon = dte.getMonth()+1; retDate = "0" + mon; } else { retDate = dte.getMonth()+1; } return retDate; }
/** Return a date string on the form "YYYY-mm-dd" for the first day of the month. */ function getBeginDate(dte) { return dte.getFullYear() + "-" + getMonthString(dte) + "-" + "01"; }
/** Return a date string on the form "YYYY-mm-dd" for the last day of the month. The last day is either 30 or 31 depending on the month. */ function getEndDate(dte) { if ((dte.getMonth()+1 == 1) || (dte.getMonth()+1 == 3) || (dte.getMonth()+1 == 5) || (dte.getMonth()+1 == 7) || (dte.getMonth()+1 == 8) || (dte.getMonth()+1 == 10) || (dte.getMonth()+1 == 12)) { return dte.getFullYear() + "-" + getMonthString(dte) + "-" + "31"; } else { return dte.getFullYear() + "-" + getMonthString(dte) + "-" + "30"; } }
/** Use the date object created on first load of the page and increase the month number part by one. Modify year as well if month number becomes more than 11 (december). */ function setNextMonth() { var nextMonth = woDate.getMonth()+1; if (nextMonth > 11) { woDate.setFullYear(woDate.getFullYear()+1, 0, woDate.getDate()); } else { woDate.setFullYear(woDate.getFullYear(), nextMonth, woDate.getDate()); } }
/** Use the date object created on first load of the page and decrease the month number part by one. Modify year as well if month number becomes less than 1 (january). */ function setPreviousMonth() { var nextMonth = woDate.getMonth()-1; if (nextMonth < 0) { woDate.setFullYear(woDate.getFullYear()-1, 11, woDate.getDate()); } else { woDate.setFullYear(woDate.getFullYear(), nextMonth, woDate.getDate()); } }
On the php/html page, when clicking on previous or next, a JavaScript function is called where the dates are set and the used as in-parameters to the backend function. The response is received and the page is updated. This is how it can look:
I have created our own web-based editor that we use to create new entries on Wohill. Very briefly spoken it works in a way that you create the entry in a textarea with the help of buttons below it which gives you the possibility to add bold text, italic text, links, images, smileys etc to the content. I will not go too deep into it this time but instead only pick out one of the functionalities. More will come later on and hopefully a full review of the admin interface someday to give you a full understanding of how it works.
Today I will show you how you can do to create a HTML-link for a selected (or no selected) text easily by clicking a button and then specifying the url. See how it works here (no fancy design).
Here is a part of the html-code on the calling page containing a textarea and a button below it for creating a link in the textarea for selected or non-selected text:
As you can see a JavaScript function is called with the argument of the textarea object 'tArea'. In the code below, a modal window is used for Internet explorer. I have not found a similar solution for Firefox, so they are handled slightly different. For Internet explorer a new page is opened and the response from it is used to create the link and put it in the textarea at the right place. For Firefox the solution has to be a bit different as already said. In this function the new window is opened but the response from it and creation of link and adding of link to the textarea is made in the popup window instead as you will see below. The 'formatTextLink' function looks like this:
/* FUNCTION FOR ADDING AN A HREF TAG IN EDITOR */ function formatTextLink(el) { /* IF INTERNET EXPLORER */ if (window.showModalDialog) { var myText = window.showModalDialog('chooseLinkUrl.html', 'name', 'dialogWidth:530px;dialogHeight:180px'); var selectedText = document.selection.createRange().text;
function returnSelected(val) { var text = document.getElementById(val).value; var trgt = document.getElementById('trgt').value;
var tagText = "<a href=\"" + text + "\" target=\"" + trgt + "\">"
if (navigator.appName == "Microsoft Internet Explorer") { // set return value window.returnValue = tagText; } else { window.opener.updateEditorAMozilla(tagText); }
// close dialog window.close(); } </script> </head>
The function 'returnSelected' builds the first part of the link tag using the fields set by the user and returns it to the function that called it (function 'formatTextLink' above). The last part happens for Internet explorer. If the browser is Firefox another function is called that handles the part that build the final url and inserts it into the textarea. This function is (as you can see above) called 'updateEditorAMozilla' and looks like this:
/* FUNCTION CALLED FROM POPUP WINDOW TO SET AN A HREF TAG IN EDITOR WHEN USING MOZILLA */ function updateEditorAMozilla(fldVal) { var tagBeginning = fldVal; var tagEnding = ""; var el = document.getElementById('tArea');
So this is it. It might feel like a lot of things to put together but it is only three different files. One html-file, one js-file and one popup-file. Add a comment if you have a question, a correction or other suggesions.
When you need to get or set data from a database to a webpage it is nowadays almost a standard to use Ajax for this to perform updates. This means that you don't have to submit an entire new webpage but instead only move the data that needs to be moved. The webpage stays as it is and gets updated asynchronously and in real-time. This is a part of web 2.0 and a great enhancement to the users compared to the old days when you actually had to request a complete new webpage from the server to send it back to you. The user sometimes had to wait for nothing at all, staring at a white screen. With Ajax you can continue working with other things on the page while waiting for the data and possible operations to take place.
Two years ago when I started looking at this I wrote these functions myself using the JavaScript XMLHttpRequest object. Using this object and functions together with some ordinary JavaScript, which updates fields on a webpage on events, makes the user experience much more appreciated. The feeling is the same today but the tools to do it have improved.
In Dojo's newest version the functionality has become even more easier than before. Only one function is needed. Here how to do it:
For this solution, download the Dojo toolkit and add this code to the head-section of your webpage. You can also access Dojo directly from AOL's CDN although you have to use a slightly different syntax. Below is code for sending an entire form as a HTTP POST to another page for further processing and also waiting for the response and act on it:
<!-- Load the dojo toolkit base --> <script type="text/javascript" src="js/dojo-release-1.1.0/dojo/dojo.js" djConfig="parseOnLoad:true, isDebug:false"></script>
<script type="text/javascript"> function eventFunction() { /* Build structure to use for posting containing functions that describe which page to post the information to that should be further processed. Here is also specified how to handle the response when it gets back. */ var kw = { url: "controller.php", load: function(data){ document.getElementById("someDiv").innerHTML = data; }, error: function(data){ console.debug("An error occurred: ", data); }, timeout: 2000, form: "someForm" }; // Form with all its elements are posted dojo.xhrPost(kw); } </script>
If you prefer to send data using GET instead, all you have to do is to use dojo.xhrGet(kw) instead.
As a developer you might want to validate some fields before submitting a form and sending it for further processing. One field may only contain numbers - it could be representing age, weight or length for example. Another field may only contain a date (on a specific format). A way to solve this is to use regular JavaScript.
Assume you have two fields that looks like this:
Number field:
Date field:
It is certainly possible to write anything in these before posting. But if you on the submit button in the form use an onclick-event to call a function instead of submitting directly using type='submit' like this:
Then you will be able to validate before posting the form. The function could look something like this:
function save() { if (document.getElementById("numberField").value == "") { alert("This field must not be empty!"); } else if (!document.getElementById("numberField").value.match(/^\d+$/)) { alert("Field must be a number!"); } else if (document.getElementById("publishDate").value == "") { alert("You must specify a date!"); } else if (!document.getElementById("publishDate").value.match(/^\d{4}(\-)\d{2}(\-)\d{2}$/)) { alert("You must specify a date on the form yyyy-dd-mm!"); } else { // Functionality to submit form via post or send data via get. } }
As you can see we are using regular expressions to see if the content in the number or date field matches a given structure. For example 'd' stands for digit (number), the plus (+) afterwards means 'any amount of numbers' - but nothing else or there will not be a match. The regular expression for the date is similar, only a bit more complex. The expression has to start with four digits (d{4}) followed by the '-' character, followed by two digits (d{2}) followed by the '-' character and finally ending with two digits again (d{2}). This ensures us that the date is on the yyyy-mm-dd format.
If you're using Dojo or some other JavaScript framework or toolkit there are predefined functions for this which makes it easy to set up this kind of validation (and much more) although there actually is some work getting it all to work. I will give some examples on this later on and also how to post or get data using dojo to backend controllers communicating with the database etc. This Ajax-functionality of Dojo is extremely easy to work with - Stay tuned!
Here's a way on how you can do simple validation on text fields. Type in some text in the input field below. When you press on tab or move the cursor out of the field the validation will take place - which consists of trimming the string and making it as propercase.
To trim a string means that leading and trailing white space is removed. Making a string as propercase means that the first character becomes capitalized. Actually this is true for each new word in the text box. Try it!
When developing a web form where you want the user to type in a date, you will have to validate the input so that it is on a form that fits the system needs. This will require the user to understand which format to use and it will require the system to validate properly and to give feedback if the format was wrong. This is not a very good solution and it does not look that good either. A neat solution is to use a date picker instead. This way the user can't make a mistake and it will be very easy to use.
I found this solution made by Julian Robichaux, the host of nsftools.com. He is a very talented developer and if you browse his site you will find lots of good free stuff to use. His date picker came in handy to use for me and I will explain how it works and how to install it here.
We have a text field in which we want to put a date chosen by the user and it has to be on a specific format. First we set the text field to be disabled so that you can not add any text to it. By pressing the button "Select date" a date dialog opens from which the user can choose a date. When clicking on the date it is pasted on a specific predefined form into the text field. This is done by using a JavaScript function which allows for different formats, which can be read more about in the JavaScript comments. Go ahead and try, click the button below!
Add this css-file and this JavaScript-file to the head section of your web page. After that all you need is this little piece of code and you're on:
We are using drag boxes at Wohill to put information that can be easily accessed to save space.
An example is the wallpaper section to the left. The three latest creations are visible directly as links. To see all the others you can click on the fourth option "more..." which opens up a mini-window containing all wallpapers links.
This mini-window is really a so-called div, an HTML-element, that is there all the time but gets visible when clicking on "more...", This saves some space but another advantage with this solution is that you can click and drag and drop this little box or window all over the webpage.
If you place the marker on the orange bar that says "Drag-and-drop" and click and hold, you can drag it all over the web page. And it will still function the same way and still have the same content.
You can easily implement this on your own and tweak it for your own purposes. What you need is a stylesheet