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.
| <script src=”js/build/util/JSON-min.js”></script> |
This is said to be addressed in the next release.
Tagged as:
ext core 3.0,
extjs,
json
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.
So we have some HTML that looks like this:
<form>
<table style=”margin:40px”>
<tr>
<td style=”width:100px”>Name: </td>
<td><input type=”text” id=”fld_name” /></td>
</tr>
<tr>
<td>Age: </td>
<td><input type=”text” id=”fld_numYears” /></td>
</tr>
<tr>
<td>Web: </td>
<td><input type=”text” id=”fld_url” /></td>
</tr>
<tr>
<td>Description: </td>
<td><input type=”text” id=”fld_description” /></td>
</tr>
<tr>
<td colspan=”2″>
<br />
<input type=”button” onclick=”checkFieldsAndSubmit()” value=”Check” />
</td>
</tr>
</table>
</form> |
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();
// Define fields here
fldArray[0] = “fld_name”;
labelArray[0] = “Name”;
valTypeArray[0] = “isEmptyString”;
fldArray[1] = “fld_numYears”;
labelArray[1] = “Age”;
valTypeArray[1] = “isNumber”;
fldArray[2] = “fld_url”;
labelArray[2] = “Web”;
valTypeArray[2] = “isUrl”;
fldArray[3] = “fld_description”;
labelArray[3] = “Description”;
valTypeArray[3] = “isEmptyString”;
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”;
}
}
}
if (str == “”) {
return true;
} else {
alert(str);
return false;
}
} |
And the other help functions:
function isNumber(str) {
if (str.match(/^\d+$/)) {
return true;
} else {
return false;
}
}
function isUrl(str) {
var v = new RegExp();
v.compile(“^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$”);
if (!v.test(str)) {
return false;
}
} |
Tagged as:
regular expression,
type,
validation
I posted a 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;
} |
Tagged as:
regular expression,
url,
validation
by Niklas Waller on January 29, 2009
in JavaScript
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 . It is a solution developed by and it is very easy to implement. See the instructions on on how to use the script.
Tagged as:
alter,
hover,
infobox,
javascript,
tooltip
by Niklas Waller on November 4, 2008
in JavaScript
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?”);
if (answer) { // Go on with the delete stuff } } |
The confirm alert box looks like this:
Tagged as:
confirm,
function,
javascript
by Niklas Waller on October 14, 2008
in JavaScript
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.
<select id=”category”>
<option value=”3″ onclick=”getCategories(3);”>ACategoryWithCategoryNumberThree</option>
</select> |
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),
<select id=”category” onchange=”getCategories(document.getElementById(‘category’).value);”>
<option value=”3″>ACategoryWithCategoryNumberThree</option>
</select> |
This way it will work for all three browsers!
Tagged as:
browser,
chrome,
event,
firefox,
ie,
onchange,
onclick
by Niklas Waller on September 30, 2008
in JavaScript
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:
| document.getElementById(‘divId’).innerHTML = response |
The div is just a tag in the body section:
<body onload=”getStuff();”> <div id=”divId” /> </body> |
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.
Tagged as:
ajax,
javascript,
timeout
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; }
if (urlStr == “” || urlStr == null) { return true; }
urlStr=urlStr.toLowerCase();
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
| var url = /(\w+:\/\/[^\s]*)/g; |
and creating html for it to create a proper link.
Tagged as:
javascript,
regular expression,
url,
validation
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.
| window.opener.someFunction(“Some text”, anotherArg); |
Anyone know a way to accomplish the modal window functionality in Firefox or other browsers than IE?
Tagged as:
modal window,
popup
We received a lately from 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 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;
if (selectedText != “”) {
document.selection.createRange().text = selectedText;
}
else {
el.focus(el.caretPos);
el.caretPos = document.selection.createRange().duplicate();
}
}
} |
The propercase function looks like this and it is slightly different from the one presented in the earlier .
function strProperCase(str) {
var retVal = str.toLowerCase().replace(/^(.)|\s(.)/g,
function($1) { return $1.toUpperCase(); });
return retVal;
} |
Tagged as:
function,
javascript,
propercase,
selection