Thursday, April 10, 2008

Javascript Tips

1) Hide a form element using javascript:
The following is a simple textbox which will be hidden by default:
<input type="text" id="text_id" name="text_name" style="visibility: hidden">
The following javascript code will make the hidden textbox visbile.
document.getElementById('text_id').style.visibility = 'visible';

2) Working with <SELECT> tags.
A simple <SELECT> tag would be created as follows:
<SELECT name="select_name" id="select_id"></SELECT> - This creates an empty drop down list.
<SELECT name="select_name" id="select_id"><OPTION value="1">1</OPTION></SELECT> - This creates a drop down with a value 1 and text as 1.
Adding a new option dynamically using javascript
var txt = '2'; // txt is the value that is set as the text of the option
var val = '2'; // val is the value that is set in the 'value' attribute of the option
var newOpt = new Option( txt, val, false); // Creating a new option object. false implies this option will not be pre-selected in the drop down on adding to the <SELECT> option.
document.<form_name>.<select_name>.options[document.<form_name>.<select_name>.options.length] = newOpt; // Assigns the newly created option to the <SELECT> list.
Getting the length of a drop down list.
document.<form_name>.<select_name>.options.length
Getting a pointer to the value that is pre-selected in the drop down currently.
document.<form_name>.<select_name>.selectedIndex.text - This returns the text that is set for the selected option.
document.<form_name>.<select_name>.selectedIndex.value - This returns the value that is set for the selected option.
Removing an element from the <SELECT> list
var x=document.<form_name>.<select_name>;
x.remove(x.selectedIndex);

3) Confirmation alert
var input_box=confirm("Do you want to delete the selected network set?");
if (input_box==true)
{
alert("You clicked OK");
}else{
alert("You clicked Cancel");
}