move values items from one multiple select box to another multiselect in javascript

JavaScript 5 Comments »

This article is about moving values or items between one multiple select box to another. Here i have given the html and the javascript code and have explained the working of it.

I have two multiple select box. One is leftSelect and another is RightSelect.

In between that i have two buttons one is to move items to the right select box and the other is to move items to the left select box.

I have statically filled the left select box with simple values and items and if you want to know how to add values dynamically then you can refer this same code where i have used .add method.

The code is

the left select box is with id=’leftSelect’ and the right select box is id=’rightSelect’

<select class='sel' id='leftSelect' multiple>
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
<option value='5'>five</option>
<option value='6'>six</option>
</select>
 
<input type='button' value='>>' onclick='move(0)'>
<input type='button' value='<<' onclick='move(1)'>
 
<select class='sel' id='rightSelect' multiple>
</select>

the right select box is empty the reason is that i am just giving a demo with empty. if you want you can fill it up with values.

the >> button will move the selected values form the left select to right select and the << button will do the reverse. For both the buttons i have called move with value 0 to mean moving to right and value 1 meaning moving left. Now you can see the javascript function which manipulates these select boxes.

function move(direction)
{
	var src = document.getElementById('leftSelect' )
	var trg = document.getElementById('rightSelect' )	
	var tem
 
	if(direction)
	{
		tem = src
		src = trg
		trg = tem
	}
 
	var selected = []
 
	for(var i in src.options)
	{
		if(src.options[i].selected)
		{
			trg.options.add(new Option(src.options[i].text, src.options[i].value));
			selected.unshift(i);
		}
	}
 
	for(i in selected)
		src.options.remove(selected[i]);
}

How does it work?
The working of this function is it copies the selected items from one select box(source) to another(target) and deletes the selected items in the source.

The first for loop will copy the items from source to target.

while copying i am storing the index of the selected items in an array in the reverse order. the reason for reversing is to maintain the indexing of the selected items. to know why reverse is used use selected.push instead of .unshift and see the effect. and the reason for copying the selected item into an array instead of instantly deleting it is because of opera browser. In this browser when an item is deleted all the elements in the select box are deselected.

The second for loop will delete the selected items from the source one by one iterating the array.

How does it work in action?
when >> button is clicked i send 0 as parameter to mean from left to right. so values from left select box are copied to to right select box and the the selected items are deleted.

The condition if(direction) will not execute so left select is source and right select is target.

When << button is clicked i want to consider right select as source and left select as target so i pass 1 as parameter to move function. now the if(selected) works so right select becomes source and left becomes target so values will move from right select to left select. The reason for using this is i want to use the same function for both the operation that is one function to move values both sides. here is another alternate for swapping source and target.

 
var src = document.getElementById( direction ? 'rightSelect' : 'leftSelect' )
var trg = document.getElementById( direction ? 'leftSelect' : 'rightSelect' )
var tem
 
/*	
if(direction)
{
	tem = src
	src = trg
	trg = tem
	}
*/

Hope you can understand the difference. Remove the commented code so that it reduces space and the code becomes small and crisp. I did it the above for my purpose and including both for better understanding. if so.

Enjoy.

how to check whether a javascript object is empty?

JavaScript No Comments »

== Option One ==

 
function isEmpty(ob){
   for(var i in ob){ return false;}
  return true;
}
 
isEmpty({a:1}) // false
isEmpty({}) // true

== Option Two ==

function isEmpty(o) {
  var o = {};
  for(var p in o) {
    if (o[p] != o.constructor.prototype[p])
      return false;
  }
  return true;
}

== Option Three ==

 
function isEmpty(ob){
   for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
  return true;
}

== Option Four ==

what about this?

 
var obj={}
Object.prototype.isEmpty = function() {
    for (var prop in this) {
        if (this.hasOwnProperty(prop)) return false;
    }
    return true;
};
alert(obj.isEmpty())

== Option five – Jquery ==

 
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

== References ==

* http://www.webdeveloper.com/forum/showthread.php?t=193474

* http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json

Similar question here about null object in javascript

* Check javascript object empty or null

why javascript history.back() toggles between two pages

JavaScript 3 Comments »

I was working in a project where each page had a back button. Because of the designers design the back button was created using anchor tag <a> and as a programmer i thought of using the back button like the following in the anchor tag.

<a href='javascript:;' onclick='window.history.back()'>Back</a>

But what had happened when i press the back button after navigating to various pages was i got locked between the last two navigated pages. It kept toggling between the last visited page and the previous page where as it is supposed to go backward step by step.

So let us say i have navigated from page 1 to 10 and now i am in page 10. When i press the back button in page 10 i came to page 9. But when i pressed the back button in page 9 again it took me to page 10 instead of taking me to page 8. So this keeps happening until i changed the code to the following.

<a href='javascript:window.history.back();'>Back</a>

After modifying to the above code all went well. The back button press worked normal which took me from page 10 all the way to page 1 when i kept on pressing the back button.

and besides the given code there was a style applied to the anchor tag and that was just float right.

Is this an issue needed attention which is to be posted in a blog? I don’t think so but thought of talking to the people to see their responses. If people know why this peculiar behaviour then please post a note of a reply or a reference or whatever which could be of assistance to all people. 🙂

US phone number validation by adding hypen automatically using javascript

JavaScript 2 Comments »

The following code will validate the US phone number format. It will not check for open and closing brackets. it will validate the following format xxx-xxx-xxxx.

Besides it will not allow any other characters other than numbers and hypen to be typed. if any other character is typed in then it is removed using the regular expression in the script.

This script was created for an instant purpose and i may expand it so that will have full control on the keypress.

I have called a function whichkey to find the keycode which is a cross browser code. Each browser handles event differently so we need to find the char code number using a cross browser function and here that is whichkey.

<script type="text/javascript">
function mask(e,f){
	var len = f.value.length;
	var key = whichKey(e);
	if(key>47 && key<58)
	{
		if( len==3 )f.value=f.value+'-'
		else if(len==7 )f.value=f.value+'-'
		else f.value=f.value;
	}
	else{
		f.value = f.value.replace(/[^0-9-]/,'')
		f.value = f.value.replace('--','-')
	}
}
 
function whichKey(e) {
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	return code
//	return String.fromCharCode(code);
}
 
</script>
<input type="text" name="phone" id="phone" 
onkeydown="mask(event,this)" onkeyup="mask(event,this)" 
maxlength="12" />

….

with the above code you can add your own code to make it more useful to you. I had made a very simple attempt to do a validation.

forcing javascript to abort – stop javascript execution at any time

JavaScript 7 Comments »

How do we abort JavaScript execution at any instance even inside a loop.

Create a function with a name jsexit or jsabort
and have this as its code

function javascript_abort()
{
   throw new Error('This is not an error. This is just to abort javascript');
}

instead of the error string which i have given you can give any string you want. This is really working well for me.

call it anywhere like javascript_abort()
for example

// assume that you have this code inside a nested function.
for(var i=0;i<10;i++)
{
     if(i==5)javascript_abort();
     alert(i);
}
//so at any place it will stop the execution.

But in IE browsers you will see an yellow exclamation to indicate that there is an error in the javascript.

Otherwise every thing is perfect i believe. In other browsers this will not appear. If you have enabled error reporting add-on for firefox then it would show a graphic notification. that too is not at all a problem.

If anybody (the users) clicks the yellow exclamation in IE they see this string as error message ‘This is not an error. This is just to abort javascript’.

But still i need an option to exit javascript execution without making IE or any other browsers that an error has occured when a new error has been thrown.

I would like to have comments, suggestion and objections about this because i would like to know what people think about this.

print div content – Print only the content of an HTML element and not the whole document

JavaScript 7 Comments »

This snippet will print the contents of any html element and not the entire page.
Get the contents of the innerhtml of the element. Here it is a div. We are going to print the contents of a div.
Define an iframe (better before this script).
This iframe is hidden on the screen by giving the style so and so.
Get a reference to the iframe’s contentwindow so that you can write the contents of the div in to the body of the iframe.
Use the close command like in the script else you can see that the browser is still loading the page even if you have completely written all the text into the content window.
So when you do close call you specify that there is no more contents to write to.
And then we make the iframe as the active window because when you print the active windows total body content will gets printed.
and then we call the print command. voila.
Without any modification this code snippet works well for me so hope it would be the same case for you guys.

The JavaScript code

var content = document.getElementById("divcontents");
var pri = document.getElementById("ifmcontentstoprint").contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();

The HTML Code

<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>

Why the need of an iframe?
as you all know when you print the whole document gets printed.
So we create a hidden new document with the help of an iframe and we assign the contents we want to print to the body of the iframe.
So the iframe will contain only the contents which we want to print.
And since the iframe is hidden everything will appear normal at the same the work is done.

Scroll DIV, HTML elements using Javascript

JavaScript 1 Comment »

Javascript Code

<script>
var sc, maxscroll, minscroll=0;
var uptime, downtime
var pixelsteps=5;
window.onload = function()
{
	sc = document.getElementById('wn3');
	maxscroll = sc.scrollHeight - sc.offsetHeight
	minscroll = 0		
}
 
function scrollup()
{
	uptime = window.setInterval('scrollUp()',1)
}
function scrolldown()
{
	downtime = window.setInterval('scrollDown()',1)
}
 
function scrollUp()
{
	if(sc.scrollTop>0)
		sc.scrollTop = sc.scrollTop - pixelsteps
	window.location.hash = sc.scrollTop		
}
function scrollDown()
{
	if(sc.scrollTop<maxscroll)
		sc.scrollTop = sc.scrollTop +  pixelsteps
	window.location.hash = sc.scrollTop
}
 
function clearscroll()
{
	if(uptime)window.clearInterval(uptime)
	if(downtime)window.clearInterval(downtime)	
}
</script>

HTML Code

 
<img src="up.gif" onmousedown="scrollup();" onmouseup="clearscroll();" /><br>
<img src="dn.gif" onmousedown="scrolldown();" onmouseup="clearscroll()"  />

== Version 2 ==

var sc, maxscroll, minscroll=0;
var uptime, downtime
var pixelsteps=2;
var delay = 10
function inscroll(src)
{
	if(arguments.length>1)pixelsteps = arguments[1]	
	if(arguments.length>2)delay = arguments[2]		
 
	sc = document.getElementById(src);
	maxscroll = sc.scrollHeight - sc.offsetHeight
	minscroll = 0		
}
 
function scrollup()
{
	uptime = window.setInterval('scrollUp()',delay)
}
function scrolldown()
{
	downtime = window.setInterval('scrollDown()',delay)
}
 
function scrollUp()
{
	if(sc.scrollTop>0)
		sc.scrollTop = sc.scrollTop - pixelsteps
}
function scrollDown()
{
	if(sc.scrollTop<maxscroll)
		sc.scrollTop = sc.scrollTop +  pixelsteps
}
 
function clearscroll()
{
	if(uptime)window.clearInterval(uptime)
	if(downtime)window.clearInterval(downtime)	
}

You have to call inscroll(‘divid’,pixelincrementvalue,delay);

replace target=_blank of anchor tag using javascrpt for w3c strict document type

JavaScript 8 Comments »

If you are using strict mode as your html document type and if you have target=_blank in your html code then wc3 gives you an error. strict mode does not accept target=_blank and they suggest to use transitional mode.

here is the javascript replacement for target=_blank. before this you have to set the rel attribute of anchor tags to “external” or anything you wish because this is used in the javascript code so see which are all the anchor tags has set the rel attribute to external .

in other words you can set the rel attribute with some value to mean that these are the tags which has to be opened in a new window.

<script type="text/javascript">
 
function target_blank()
{
 
     var anchors = document.getElementsByTagName("a");
     for (var i=0; i<anchors.length; i++) 
     {
          if ((anchors[i].href!='') && anchors[i].rel == "external")
               anchors[i].target = "_blank";
     }
}
 
window.onload = target_blank;
 
</script>

here is a script with which you can make a single anchor tag open in new window using javascript

<a href="some.html" 
onclick="window.open(this.href); return false;" 
onkeypress="window.open(this.href); return false;">
Open in new window using javascript</a>

static variables in javascript

JavaScript 5 Comments »

static variables in javascript

In javascript functions and objects work in the same manner. Functions are also objects.
so a function can have a member variable like in objects.
A member variable will retain its value between function calls.
So this aspect is used for having a static variable in javascript.
Actually there is no option like static variables in javascript. so here the member variable server as a static variable in javascript.

here is one simple script which uses a static variable to maintain a counter

<script>
function addmore()
{
	if(!addmore.counter)addmore.counter = 0;
	addmore.counter++;
	alert(addmore.counter)
}
 
addmore();
addmore();
 
</script>

or here is another version

<script>
function addmore()
{
	if(!this.counter)this.counter = 0;
	this.counter++;
	alert(this.counter)
}
 
addmore();
addmore();
 
</script>

i have used this for multiple file uploads where there will be an addmore button and a variable to maintain the count of number of uploads to display and once this.counter is greater than 10 then i alert a message that uploads cannot be more than 10.

some people had an idea that why done we use like the following instead of using it like a member function

<script>
var counter=0
function addmore()
{
	counter++;
	alert(counter);
}
addmore();
addmore();
 
</script>

my answer is not to mess up the code with too many declarations which uses the word var…
after a long time we would wonder which variable is for which function
and if the variable is with respect to the context of the process then that will a good practice of maintaing standards and more meaningful.

if you would like to suggest an alternate please comment on this because i would like to know more if there is anything beyond my scope on this.

find absolute position of an html element

JavaScript 3 Comments »

Html elements are displayed cascading by default. So every element appears one after the other and it is the same with nested elements. I mean elements within another element.

I want to find the exact absolute position of an element. In other words i want to find the exact x,y of an element in the html page if you could consider the html page as a graph.

I used left and top but it will always give the x and y with respect to the parent and not to the window or the body tag which is the first parent for all visible elements. Then i read about the property offsetLeft and offsetTop but this too is with respect to the parent.

So find the parents left + its parent left + its parent till you reach the top then you will get the left of any element. The same way for finding the top that is y. here is the function which will give you the x,y/absolute position of any element.

But when i used float left property i found this function returned a different value so please check when using float left option. anyway …

function findAbsolutePosition(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
//returns an array
}


and to my surprise i found the following link when i tried to find something like this to check my work.

http://www.quirksmode.org/js/findpos.html

I use this site to cross check my snippets in javascript if present. This is one useful site i have found which analyses beyond the scope.

Entries RSS