Tuesday, February 19, 2013

Sharepoint 2010 - Set value in textbox in SP forms with jQuery

Putting values in html textboxes is not as easy in SharePoint forms as it is in a regular html forms.It isn't difficult, but it takes a while to figure it out.

In ordinary html form, if you define your textbox like this:

<input type="text" id="txt1">

then you can set value in that textbox with javascript like this:

<script>
window.onload=function(){
        var txt1 = document.getElementById("txt1");
        txt1.value = "MyText";
};
</script>

Well, with SharePoint, things aren't exactly the same. In SharePoint form, you can't just get element by its id, because you can't read its id, because it is server-generated. Actually, you can read it, but only after you load the page in browser, and you will find out that it is a very long guid.It is not recommendable to access elements using this id.

So, if you open your form in SharePoint Designer, you can see how table rows are defined in html. For examlpe, here is the row of form's "Title" element:





 You can see here that your textbox has id="ff1{$Pos}".

If you want to read that element and put some value in it, then you can do the following:

1. Give that row an ID (for example: id="myRow").



2. Now, in javascript, you can do this (jQuery library must be included on the page):

<script>
window.onload=function(){
        var spRow = document.getElementById("myRow");
        var spInput = element.getElementsByTagName("input")[0];
        spInput.value = "SomeValue";

};
</script>

And text "SomeValue" will appear in your form, in field "Title" when the page loads.

No comments:

Post a Comment