JavaScript

Count number of possible combinations of a word

by Niklas Waller on November 18, 2010

in JavaScript

I was bored so I decided to create a simple Javascript function that given a word in an input field calculcates the number of possible combinations of the characters in that word. At least if you strictly treats every character as unique. If you provide the same character more than once, in reality this will give fewer combinations.

For example the word ‘”ab” gives 2 possible combinations – “ab” and “ba”.

The word “abc” gives 6 – “abc”, “acb”, “bac”, “bca”, “cab”, “cba”.

“abcd” gives 24 combinations and “abcdef” gives 720 different combinations.

I would like to create a function that takes into account the case when one or several characters are present more than once, but that will be for a later occasion. Or if you as a visitor have that function, please share! Here’s the code for this example anyway.
And also be aware of that leading and trailing white spaces are removed but not white spaces in a sentence. I know, lazy programmer, but it’s late ;-)

<script type=”text/Javascript”>

function trimStr(fld) {
word = document.getElementById(fld).value;
word = word.trim();
document.getElementById(fld).value = word;
}

function numberOfCombinations(word) {
var numComb = 1;
if (word.length == 0) {
return “No string provided”;
} else {
for (i=word.length;i>=1;i–) {
numComb = numComb * i;
}
return numComb;
}
}

function printNumComb(resultDiv, fld) {
document.getElementById(resultDiv).innerHTML = numberOfCombinations(document.getElementById(fld).value)
}
></script>

Use these functions like this:

<input id=”word” type=”text” /> <input onclick=”trimStr(‘word’);printNumComb(‘resultDiv’,'word’);” type=”button” value=”Calculcate” />

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

Which JavaScript Framework do you use?

by Niklas Waller on May 6, 2010

in JavaScript

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?

Prototype
Dojo
Ext JS
Script.aculo.us
Rico
MooTools
jQuery
YUI
SPRY
SproutCore
JavaScriptMVC
DOMAssistant
MochiKit
DED|Chain
ARCHETYPE
qooxdoo
Rialto
UIZE
Helios

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

2 comments

Mimicking the Google Search box

by Niklas Waller on April 22, 2010

in JavaScript

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

Here’s an example script that works:

<html>
<head>
<script type=”text/javascript” src=”js/jquery.js”></script>

<link rel=”stylesheet” href=”js/jquery-autocomplete/demo/main.css” type=”text/css” />
<link rel=”stylesheet” href=”js/jquery-autocomplete/jquery.autocomplete.css” type=”text/css” />
<script type=”text/javascript” src=”js/jquery-autocomplete/lib/jquery.bgiframe.min.js”></script>
<script type=”text/javascript” src=”js/jquery-autocomplete/lib/jquery.dimensions.js”></script>
<script type=”text/javascript” src=”js/jquery-autocomplete/jquery.autocomplete.js”></script>

<script type=”text/javascript”>
$(document).ready(function(){
var data = “blue green white red yellow black pink purple brown orange”.split(” “);
$(“#myInput”).autocomplete(data);
});
</script>

</head>
<body>
<div style=”margin:50px”>
autocomplete search box: <input id=”myInput” /> (try b)
</div>
</body>
</html>

See this page with the above piece of code.

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.

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

Setting the width and height of a div with Javascript

by Niklas Waller on January 7, 2010

in JavaScript

It is tempting to do it like this:

document.getElementById(‘idOfTheDiv’).style.width = newWidth;

However this won’t work and if you think about it, it is not strange either.

This is how to declare the width and height of a div in a stylesheet:

aDiv {
width: 200px;
height:100px;
}

And by looking at this we can see why the first example doesn’t work and how to fix it. I.e. add ‘px’ when setting the width like this:

document.getElementById(‘idOfTheDiv’).style.width = newWidth + ‘px’;

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

Row hovering a table with background colors

by Niklas Waller on November 19, 2009

in JavaScript

Row hovering:

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=’#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>

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

Display a text with columns in JavaScript

by Niklas Waller on September 3, 2009

in JavaScript

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

pos1 = strrpos(part1 , ‘<’);
pos2 = strrpos(part1 , ‘>’);

if ((pos1 < pos2) || (pos1 === false)) {
return cut; /* no html tag around */
}

pos3 = strpos(text , ‘>’ , cut1 + 1);

if (pos3 !== false) {
return pos3; /* end of middle html tag */
} else {
return cut; /* unbalancing < > */
}
}

function print_colums(text, column_spacing, column_width, columns) {
var mid_pos = split_pos(text);
var col_str = “”;

col_str = “<table cellpadding=’0′ cellspacing=’0′><tr valign=’top’>”;

if (columns == 1) {
col_str = col_str + “<td class=’textContent’ style=’width:” + column_width + “px’>” + text + “</td><td style=’” + column_spacing + “px’></td><td class=’textContent’ style=’width:” + column_width + “px’></td>”;
} else if (columns == 2) {
col_str = col_str + “<td class=’textContent’ style=’width:” + column_width + “px’>” + text.substr(0,mid_pos) + “</td><td style=’width:” + column_spacing + “px’></td><td class=’textContent’ style=’width:” + column_width + “px’>” + text.substr(mid_pos + 1) + “</td>”;
}

col_str = col_str + “</tr></table>”;

return col_str;
}

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

2 comments

Use PHP functions in JavaScript with PHP.JS

by Niklas Waller on August 27, 2009

in JavaScript

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.

Great work!

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

Validate your JavaScript with JSLint

by Niklas Waller on July 16, 2009

in JavaScript

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”;
}
}

if (str == “”) {
return true;
} else {
alert(str);
return false;
}
}

Here is the feedback/response/validation:

Error:
Implied global: alert 29, document 6 10 14, isNumber 10, orgStr 14 16 17 20 22

Problem at line 6 character 52: Use ‘===’ to compare with ”.

if (document.getElementById(fldName).value == “”) {

Problem at line 26 character 13: Use ‘===’ to compare with ”.

if (str == “”) {

Problem at line 1 character 55: Unmatched ‘{‘.

function validateFields(fldName,labelName,validation) {

Global validateFields

1 validateFields(fldName, labelName, validation)
Variable char1Pos, char2Pos, str
Unused iChar

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

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:

$json = ‘{“status”:1,”header”:”‘ . $row['header'] . ‘”,”subHeader”:”‘ . $row['subHeader'] . ‘”,”image”:”‘ . $row['img'] . ‘”,”textbody”:”‘ . $row['textbody'] . ‘”}’;

And it is decoded using Ext’s decoding function:

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.

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

Rounding numbers in JavaScript

by Niklas Waller on June 29, 2009

in JavaScript

Simple:

var x = 3.50;
Math.round(x);// Output: 4

 

Simple (negative):

var x = -3.40;
Math.round(x);// Output: -3

 

Rounded upwards:

var x = 5.25;
Math.ceil(x);// Output: 6

 

One decimal:

var x = 5.26;
Math.round(x*10)/10;// Output: 5.3

 

Two decimals:

var x = 6.789323;
Math.round(x*10)/10;// Output: 6.79

Try it yourself below using this simple form (use the dot as a decimal separator):

Number:
  Number of decimals:

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment