Friday, June 13, 2008

Using simple JavaScript in SharePoint

JavaScript is the headache for most of the .Net users.
And when it comes to SharePoint than it become worst.

Here I am posting how to use JavaScript to find element in SharePoint webpart or custom control.

Note: here we are using (usercontrol). ascx page for creating webpart or custom control.
For information check this link.

In generic ASP.Net we can use
document.getElementsById” or
document.getElementsByName
to finding any controls or object.

But in SharePoint we cannot do the same.
In SharePoint we have to do something extra.

Here the details with example.
First what we have to do is that declare a variable for document.forms[0].
var objForm = document.forms[0];

Now we have loop through all the element of that document.
So for loop execute until all elements parsed.
We can find all elements by objForm.elements.length
Now in each control if you check source of that page which contain webpart then you can find
Each and every control has type
Like text box has type “Text”
Dropdown has type “Choice”
And etc…
Find particular object in that for loop like this way (this example for text box)
if (objForm.elements[j].type == "text" && objForm.elements[j].id.indexOf("_dtpDateTimeDate") != -1)

means an object with type is “text” and its id contains “_<<the id given by you>>”
that will be your object which you are looking for.
You can get its value by (alert is just to prompt)
alert(objForm.elements[j].value);

You can set and get value of that control or object.

You can call this script by onload of the window or by adding attribute of control and all that.

Here only thing to check is that
You have to add this script tag for your script to work in different browser.
<script language="javascript" type="text/javascript"> var isNS = (navigator.appName == "Netscape") ? 1 : 0; if(navigator.appName == "Netscape") document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP); function mischandler(){ return false; } function mousehandler(e){ var myevent = (isNS) ? e : event; var eventbutton = (isNS) ? myevent.which : myevent.button; if((eventbutton==2)||(eventbutton==3)) return false; } document.oncontextmenu = mischandler; document.onmousedown = mousehandler; document.onmouseup = mousehandler; </script>

Here is the whole script

<!—first tag for cross browser functionality - ->
<script language="javascript" type="text/javascript"> var isNS = (navigator.appName == "Netscape") ? 1 : 0; if(navigator.appName == "Netscape") document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP); function mischandler(){ return false; } function mousehandler(e){ var myevent = (isNS) ? e : event; var eventbutton = (isNS) ? myevent.which : myevent.button; if((eventbutton==2)||(eventbutton==3)) return false; } document.oncontextmenu = mischandler; document.onmousedown = mousehandler; document.onmouseup = mousehandler; </script>

<!—to start our script - ->
<script language="javascript" type="text/javascript">

//getting document form
var objForm = document.forms[0];

//calling this function on onload

window.onload = getobjectvalue;

//here I’m checking the date because date will be the most complex
//if you check the source then SharePoint date picker is itself textbox and an image with JavaScript
//so we can populate sharepoint date value by this and make any validation with date.
// we can also call this function on date changed or any button click. (Basic fundamentals)

function getobjectvalue();
{
for (j = 0; j < objForm.elements.length; j++)
{
if (objForm.elements[j].type == "text" && objForm.elements[j].id.indexOf("_dtpDateTimeDate") != -1)
{
Var TaskStartDate = objForm.elements[j].value;
alert('task start date : '+ TaskStartDate );
}
}

}
</script>

You can also use this script in custom control prepared with (usercontrol) .ascx.

Have fun.....

7 comments:

Anonymous said...

So please, how can I make reference to external js file inside core.js
I defined this function at the end of core.js

function include_dom(script_filename) {
var html_doc = document.getElementsByTagName('head').item(0);
var js = document.createElement('script');
js.setAttribute('language', 'javascript');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', script_filename);
html_doc.appendChild(js);
return false;
}

but when invoking, it cause a problem

Nilios said...

Does this work on DispForm? I looked through the source the FieldType is SPFieldCalculated. Is that what I am searhing for in place of "text" as stated on your code? Also, because this is on the DispForm (using tables to display the information) there is no ID set unless ID=SPFieldCalculated is what I am looking for however I have a few calculated fields on this list.

SharePoint Kings said...

quick hint using jquery

find h3 which contents your field name like if your field name is "Field 1" then i.e.
$("h3:contains('Field 1')")

get parent() or parent().parent() once you get that object then find your value

hope this helps

Nilios said...

I never used the get parent().parent() script. I tried to use the jquery.next function but it doesn't seem to work.

Have you ever seen instances where javescript code won't work when placed underneath a table in dispForm.aspx?

Nilios said...

does this make sense?

Var sField1 = $('H3:contains("DashboardKey")').closest('TD').next('TD').text();

if DashboardKey is my field name?

I have tried this but it didn't work. Can you see if I missed something here?

SharePoint Kings said...

Nilios,

theoretically your syntax looks perfect. it will give you 'TD' of what you are looking for.

our suggestion
try to add [0] as it might chance to get multiple h3. script may be treated it like this way.
so i.e. $('H3:contains("DashboardKey")')[0].closest('TD').next('TD')


another way is break them.

first use $('H3:contains("DashboardKey")') or $('H3:contains("DashboardKey")')[0] in one object
then find its closed('TD') in one variable then find its next 'TD' and each time put alert or debug script so you got to know weather you are getting proper values or not and if not you can find where are you breaking.

you can also use
$('H3:contains("DashboardKey")').each(function(){

});

to loop through all the object

Nilios said...

Thanks SK!

Both methods work. For the original code I sent, go figure what I did was change the capital V in Var to lower case V (to make it var) and it worked! Not sure why that matters but it works now.




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com