Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.
Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, March 30, 2012

Create a Modal Dialog Window using JavaScript

<script language="javascript" type="text/javascript">
   var answer = window.showModalDialog("Your Page URL","","dialogWidth:700px; dialogHeight:700px; center:yes");
    </script>

Thursday, March 22, 2012

Binding Images to SharePoint or Asp.Net GridView BoundField using JavaScript

 function getImagestoGrid()
{
                var rows = document.getElementsByTagName('td');
                 var numRows = rows.length;
                 for (var i = 0; i < numRows; i++)
                {
                                if(rows[i].innerHTML=="In Progress")
                                {
                                                rows[i].innerHTML="<Img src='http://vlnrm:100/Shared Documents/Research and Development/Images/In Progress.jpg' width='25' height='25' Title='In Progress'>";
                                }
                               
                                if(rows[i].innerHTML=="Completed")
                                {
                                                rows[i].innerHTML="<Img src='http://vlnrm:100/Shared Documents/Research and Development/Images/Completed.jpg' width='25' height='25' Title='Completed'>";
                                }
                               
                                if(rows[i].innerHTML=="Deferred")
                                {
                                                rows[i].innerHTML="<Img src='http://vlnrm:100/Shared Documents/Research and Development/Images/Deferred.jpg' width='25' height='25' Title='Deferred'>";                 
                                }

                }
}
_spBodyOnLoadFunctionNames.push("getImagestoGrid");

Tuesday, March 20, 2012

Sending Subject & Body to Outlook in HTML Format using JavaScript

<html>
<head>
<script language='Javascript'>
function OpenOutlook()
{
   
try
{

var outlookApp = new ActiveXObject("Outlook.Application");
var nameSpace = outlookApp.getNameSpace("MAPI");
mailFolder = nameSpace.getDefaultFolder(6);
mailItem = mailFolder.Items.add('IPM.Note.FormA');
mailItem.Subject="Me";
//mailItem.To = "me@me.com";
mailItem.HTMLBody = document.getElementById('tdBody').innerHTML;
mailItem.display (0);
}
catch(e)
{
alert(e);
// act on any error that you get
}

}
</script>

</head>
<body>
<form>
<table width='100%' cellpadding='0' cellspacing='0' >
<tr>
<td id='tdBody'>
<table width='100%' cellpadding='0' cellspacing='0' bgcolor='Aqua' border='1' >
<tr><td>FName</td><td>Prasad</td></tr>
<tr><td>City</td><td>Hyderabad</td></tr>
<tr><td>Telno</td><td>12345678</td></tr>
</table>
</td>
</tr>
</table>

<a href='JavaScript:OpenOutlook();'>Sample</a>

</form>
</body>
</html>

Tuesday, February 14, 2012

Printing the Today's Date using JavaScript

<html>
<head>
<title>
</title>
<script type="text/javascript">

function getTodaysDate()
    {
         var today=new Date(); // Initialize Date in raw form
var date=today.getDate(); // Get the numerical date
var year=today.getYear(); // Get the year
var day = today.getDay(); // Get the day in number form (0,1,2,3,etc.)
var month=today.getMonth()+1; // Get the month
var suffix="";
// Make day number value correspond to actual day name
var dayName=new Array(7)
dayName[0]="Sunday";
dayName[1]="Monday";
dayName[2]="Tuesday";
dayName[3]="Wednesday";
dayName[4]="Thursday";
dayName[5]="Friday";
dayName[6]="Saturday";

// Add suffix to date (1st, 2nd, 4th, etc.)
if (date==1) suffix=("st");
else if (date==2) suffix=("nd");
else if (date==3) suffix=("rd");
else if (date==21) suffix=("st");
else if (date==22) suffix=("nd");
else if (date==23) suffix=("rd");
else if (date==31) suffix=("st");
else suffix=("th");
var monthName="";
// Make month number correspond to month name
if (month==1) monthName=("January");
else if (month==2) monthName=("February");
else if (month==3) monthName=("March");
else if (month==4) monthName=("April");
else if (month==5) monthName=("May");
else if (month==6) monthName=("June");
else if (month==7) monthName=("July");
else if (month==8) monthName=("August");
else if (month==9) monthName=("September");
else if (month==10) monthName=("October");
else if (month==11) monthName=("November");
else monthName=("December");

//document.write(dayName[day] + ", " + monthName + " " + date + suffix + ", " + year);
document.getElementById("divDate").innerHTML=date + suffix+" "+ monthName+" " + year;

    }


</script>


</head>
<body onload="getTodaysDate();">
<div id="divDate"></div>
</body>
</html>



Monday, December 05, 2011

Encoding html using JavaScript escape and unescape


There are a couple of reasons that you may want to encode some (or all) of your source html, these include:
  • Slightly increased security - by protecting your source from being easily read you are making it more difficult for anyone trying to find a workaround to your site (includes spoofing payments and gaining access to members areas)
  • Protection for automated non-javascript enabled crawlers - many of these are used to harvest email addresses from websites to add to spam mailing lists, and encoded email address will not be recognised as they cannot process the javascript.
There is also a downside however. Users of your website may well be veiwing it on a non-javascript enabled browser or have javascript turned off (usually done to avoid malicious scripts and auto-popups), if the site user is unable to process the javascript then they too will be unable to read the information that has been encoded and it will appear missing from the page.


Top of Form
Enter the text to encode here:
 


Encoded html:
 <script type="text/javascript">document.write(unescape("

"));</script>

Bottom of Form
How it's done
It's encoded by using the escape() function and then further special characters are encoded using the following routine:
   function encodeMyHtml() {
     encodedHtml = escape(encodeHtml.htmlToEncode.value);
     encodedHtml = encodedHtml.replace(/\//g,"%2F");
     encodedHtml = encodedHtml.replace(/\?/g,"%3F");
     encodedHtml = encodedHtml.replace(/=/g,"%3D");
     encodedHtml = encodedHtml.replace(/&/g,"%26");
     encodedHtml = encodedHtml.replace(/@/g,"%40");
     encodeHtml.htmlEncoded.value = encodedHtml;
   }
It is then dispayed by utilising the unescape() fuction which will turn it all back into html:
<script type="text/javascript">document.write(unescape(" my encoded html "));</script>

Introduction to Forms


show page contents
show site navigation
Loading site navigation; please wait...
See section 8J of the book. However, this page contains a more complete overview of how to write a basic form validation script.
On this page I give the code you need for checking user input in a form. Using these bits of code, you can write your own scripts to validate forms
I can't give you a complete script, because each form and each check are different. You'll have to use the elements I explain on this page to build your own script. I created an example form and script that you can study to get the hang of it.
On this page I discuss the limitations of using JavaScript to check a form, then I'll explain the onsubmit event handler, followed by the few methods and properties of the form itself. Then it's time for accessing the form elements and the specific syntax for accessing the user defined value of form elements.
See also Jeff Howden's excellent article Forms & JavaScript Living Together in Harmony for some of the most common usability errors and their solutions.

Limitations

First of all, you should have a clear idea of what happens when a user submits a form that has a JavaScript validation script:
  1. The form is checked by a JavaScript like the one described below. If the script finds a mistake the submission is halted here. The user sees an alert and is asked to re-enter some data.
  2. If nothing is wrong—or if JavaScript is disabled—the form is sent to the server and is processed by a CGI script.
  3. If the CGI script finds a mistake it generates some HTML with an error message and sends it back to the user. In this case the user has to go back to the form, re-enter some values and again submit it.
  4. If no mistakes are found, the CGI script does whatever it has to do with the data and directs the user to a Thank You page.
As you see, the form is checked for mistakes twice: by the JavaScript and by the CGI script. The CGI check always works, since CGI is server side. The JavaScript check only works when the user has JavaScript enabled. It follows that the CGI check is the most reliable: it always works regardless of what browser is used. Then why use a JavaScript check too?
The JavaScript check is very useful in addition to the CGI check because it can catch mistakes before the form is actually sent to the server. Thus the user doesn't have to use his back button to return to the form, something that may cause confusion, and then search for the incorrect form field, which may cause even more confusion. Therefore the JavaScript check is more user friendly than the CGI check.
In addition, when you use JavaScript the server doesn't need to spend quite so much time in error handling and is thus a little quicker. This only matters if you have lots and lots of forms, but it's good to keep it in mind.
So JavaScript is not a fail-safe method of catching mistakes, but it is very useful as an addition to CGI checks since it lightens the load on the server and is more user friendly. Therefore I recommend using both JavaScript form checks and CGI form checks. This way, you get both user friendliness and security.

onsubmit

When using JavaScript to check a form, the first thing you need is the onsubmit event handler. This event handler specifies a script that is executed when the user submits the form. That script is where you check whether certain fields have a value, whether the user has checked at least one checkbox, and any other checks you deem necessary.
The general syntax is:
<form action="something.pl" onsubmit="return checkscript()">
where checkscript() is the name of the script. This script should return either true or false. If false is returned, the form will not be submitted. If either true or false is returned the script stops.
So the general script becomes something like:
function checkscript() {

        if (some value is/is not something) {

               // something is wrong

               alert('alert user of problem');

               return false;

        }

        else if (another value is/is not something) {



               // something else is wrong

               alert('alert user of problem');

               return false;

        }



        // If the script makes it to here, everything is OK,

        // so you can submit the form



        return true;



}
Of course this function can become much more complex if you have to check a complicated form with a lot of radio buttons and things. The general idea remains the same, however: You go through the elements, check whatever you want to check and as soon as you find any mistake, you return false, after which the script stops and the form is not submitted.
Once you've found a mistake, you should notify the user of the problem. This used to be done by an alert, but nowadays you can generate error messages and insert them next to the form field.
Only at the very end of the script, when you have checked all elements and encountered no mistakes, you return true, after which the form is submitted.

Form methods and properties

JavaScript has a few built-in methods and properties for dealing with forms. Three of them are especially important:
You can submit a form by using the submit() method. To submit the first form on the page, do
document.forms[0].submit()
Please note that when a form is submitted by JavaScript the onsubmit event handler is never executed.
To reset the form, do
document.forms[0].reset()
I assume, but have not tested, that the onreset event handler isn’t executed either if you reset the form through JavaScript.
Finally, you can change the ACTION of a form if you want to:
document.forms[0].action = 'the_other_script.pl';
This can come in very handily if a form has to be submitted to another script in some cases.

Accessing the form elements

The form validation script needs to access the form in the HTML page to determine what values the user has filled in. So first we have to enter the form by means of the Level 0 DOM. The general syntax for accessing a form element is:
document.forms[number].elements[number]
When the page is loaded, JavaScript makes an array forms in which it puts all the forms that are on the page. The first form is forms[0], the second is forms[1] etc.
Each form has another array in which JavaScript puts all the elements in the form. The first elements is elements[0], the second elements[1] etc. Every <input>, <select> and <textarea> is an element.
In some cases, it's better to use the names of the forms and elements. In HTML, you have to give a name to each form and each element, like:
<form name="personal" action="something.pl" onsubmit="return checkscript()">

<input type=text size=20 name=name>



<input type=text size=20 name=address>

<input type=text size=20 name=city>

</form>
Now you can access these elements by:
document.personal.name

document.personal.address

document.personal.city
The advantage of using names is that you can put all elements somewhere else in the page and still have a working script, while a script using numbers will have to be changed. After all, the input box city is document.forms[0].elements[2] in the example above, but when you suddenly put it at the top of the form, it becomes document.forms[0].elements[0] and you have to change the script.

Determining values

Of course, the most important thing is to find out what the user has filled in or checked in the form. At other times you might want to fill in something in the form.
Below are snippets of scripts that help you access form elements. All of them are meant to send the user input to the variable user_input. After you've done that, you can check this value for whatever you want.
If you'd like to study a practical example, see the example form and script.

Texts, textareas and hidden fields

Very simple:
user_input = document.forms[0].text.value
where text is the name of the text field, textarea or hidden field. The value of this element gives the text, so we transfer it to user_input.
Writing is also possible:
document.forms[0].text.value = 'The new value';

Select boxes

Select boxes are simple too:
user_input = document.forms[0].select.value;
To change the selected option in a select box, you have to change its selectedIndex, like
document.forms[0].select.selectedIndex = 2;
Now the third option in the box is selected.
Old browsers
In old browsers, select boxes didn't yet have a value property. Back then, this was the way to find the value of a select box:
var selectBox = document.forms[0].select;

user_input = selectBox.options[selectBox.selectedIndex].value
First, we need to find out which option the user has selected. document.forms[0].select.selectedIndex gives us the number of the selected option. JavaScript has created an array options which contains all options of the select box. So we ask for the selected option in this array and take the value of it, which we transfer to user_input.

Checkboxes

Checkboxes need a slightly different approach. We already know their values, but want to know whether the user has checked them. The checked property tells us. It can have two values: true or false.
Now we do:
if (document.forms[0].checkbox.checked) {

        user_input = document.forms[0].checkbox.name

}
in which checkbox is the name of the checkbox. If the checkbox is checked, we take its name (or its value, if you need that bit of data) and transfer it to user_input.
To check a checkbox, set its property checked to true:
document.forms[0].checkbox.checked = true

Radio buttons

Unfortunately it's not possible to see at once which radio button in a group the user has checked. You need to go through all radio's and see which one's checked property is true.
for (i=0;i<document.forms[0].radios.length;i++) {

        if (document.forms[0].radios[i].checked) {

               user_input = document.forms[0].radios[i].value;

        }

}
where radios is the name of the group of radio buttons.
Note that document.forms[0].radios is an array filled with all radio buttons. Loop through all of them and see if it is checked. If one is, transfer the value of that radio button to user_input.
document.forms[0].radios.length gives the number of radio buttons. For each radio button, we see if it is
To check a radio button, set its property checked to true:
document.forms[0].radios[i].checked = true;

How to get value from TextBox, RadioButtonList, DropDownList, CheckBox through JavaScript


Introduction

In day to day life generally we need to get values from asp.net server controls through JavaScript while developing web applications. I found several questions on the internet for the same subject. In this article I am going to show how to get values from asp.net controls like TextBox, RadioButtonList, DropDownList, CheckBoxes.
Getting TextBox Value in JavaScript

.aspx page code
Following code will render a TextBox and a Button control as displayed in the picture above.
                       <table>



                            <tr>



                                <th colspan="2" align="left">



                                    Getting TextBox Value in JavaScript:



                                </th>



                            </tr>



                            <tr>



                                <td>



                                    <asp:TextBox ID="txt1" runat="server"></asp:TextBox>



                                </td>



                                <td>



                                    <input type="button" value="Submit" onclick="GetTextBoxValue('<%= txt1.ClientID %>')" />



                                </td>



                            </tr>



                        </table>


JavaScript function
Following code is JavaScript function to get value from TextBox control.
// Get TextBox value



        function GetTextBoxValue(id)



        {



            alert(document.getElementById(id).value);



        }


Getting DropDownList/ListBox selected value

Following code will render a DropDown (Html select control) and a button as displayed in the picture above.
.aspx code
<table>



                            <tr>



                                <th colspan="2" align="left">



                                    Getting DropDown/ListView Value



                                </th>



                            </tr>



                            <tr>



                                <td>



                                    <asp:DropDownList ID="dropDown" runat="Server">



                                        <asp:ListItem Text="Item 1" Value="1" Selected="True"></asp:ListItem>



                                        <asp:ListItem Text="Item 2" Value="2"></asp:ListItem>



                                        <asp:ListItem Text="Item 3" Value="3"></asp:ListItem>



                                    </asp:DropDownList>



                                </td>



                                <td>



                                    <input type="button" value="Submit" onclick="GetDropDownValue('<%= dropDown.ClientID %>')" />



                                </td>



                            </tr>



                        </table>

JavaScript Code
Following is the JavaScript function to get the value from DropDown control
// Get DropDown value



        function GetDropDownValue(id)



        {



            alert(document.getElementById(id).value);



        }


Getting RadioButtonList selected value

Following code will render RadioButtons and a button as displayed in the picture above.
.aspx code
<table>



                            <tr>



                                <th colspan="2" align="left">



                                    Getting RadioButton Value



                                </th>



                            </tr>



                            <tr>



                                <td>



                                    <asp:RadioButtonList ID="radiobuttonlist1" runat="Server" RepeatLayout="flow" RepeatDirection="horizontal">



                                        <asp:ListItem Text="Radio 1" Value="1" Selected="True"></asp:ListItem>



                                        <asp:ListItem Text="Radio 2" Value="2"></asp:ListItem>



                                        <asp:ListItem Text="Radio 3" Value="3"></asp:ListItem>



                                    </asp:RadioButtonList>



                                </td>



                                <td>



                                    <input type="button" value="Submit" onclick="GetRadioButtonValue('<%= radiobuttonlist1.ClientID %>')" />



                                </td>



                            </tr>



                        </table>

JavaScript Code
Following is the JavaScript function to get the selected value from RadioButtons
// Get radio button list value



        function GetRadioButtonValue(id)



        {



            var radio = document.getElementsByName(id);



            for (var ii = 0; ii < radio.length; ii++)



            {



                if (radio[ii].checked)



                    alert(radio[ii].value);



            }



        }


Getting CheckBox checked status

Following code will render a checkbox and a button as displayed in the picture above.
.aspx code
<table>



                            <tr>



                                <th colspan="2" align="left">



                                    Getting Checkbox Value



                                </th>



                            </tr>



                            <tr>



                                <td>



                                    <asp:CheckBox runat="server" ID="checkBox1" Text="Check Box" />



                                </td>



                                <td>



                                    <input type="button" value="Submit" onclick="GetCheckBoxValue('<%= checkBox1.ClientID %>')" />



                                </td>



                            </tr>



                        </table>

JavaScript Code
Following is the JavaScript function to get value from a Checkbox.
 // Get Checkbox checked status



        function GetCheckBoxValue(id)



        {



            alert(document.getElementById(id).checked);



        }



        


Show/Hide Text using

Following code will render three buttons and a table element having some text as displayed in the picture above.
.aspx code
<b>Show/Hide display text</b><br />



                        <input type="button" value="Toggle Display Following Text" onclick="ToggleFollowingText('table1')" />



                        <input type="button" value="Show Only" onclick="ShowOrHide('show', 'table1')" /> 



                        <input type="button" value="Hide Only" onclick="ShowOrHide('hide', 'table1')" />



                        <table id="table1">



                            <tr>



                                <td style="background-color:Aqua">



                                    This is my hidden text, You can play with it by clicking above button.



                                </td>



                            </tr>



                        </table>


JavaScript Code
Following is the JavaScript function to toggle display the table and show and hide element the table.
// Show/Hide element



        function ToggleFollowingText(id)



        {



            document.getElementById(id).style.display == '' ? document.getElementById(id).style.display = 'none' : document.getElementById(id).style.display = '';



        



        }



        



        // Either show or hide element 



        function ShowOrHide(condition, id)



        {



            if (condition == 'show')



                document.getElementById(id).style.display = '';



            else if (condition == 'hide')



                document.getElementById(id).style.display = 'none';



        



        }