1,804 articles and 14,767 comments as of Tuesday, April 19th, 2011

EndUserSharePoint has combined resources with NothingButSharePoint.com. You can now find End User (Mark Miller), Developer (Jeremy Thake) and IT Pro SharePoint (Joel Oleson) content all in one place!

This site is a historical archive and is no longer being updated. Please update your favorites, bookmarks and RSS feeds.

NothingButSharePoint.com
Tuesday, July 27, 2010

SharePoint: Extending the DVWP – Part 22: Creating Title Based on Other Fields with jQuery

Author: Jim Bob Howard

When we were loading data into our relationship lists, we set the site columns to not required so that we could load one column at a time in the datasheet view. We talked about the fact that it would be a major headache to try to automate filling the Title field with a workflow at that time. And, we couldn’t even use a Calculated column because Lookup columns aren’t visible to a Calculate column.

But what about ongoing maintenance of these lists?

If your environment is such that an update will require loading a completely new list to one of the drop-downs, you will need to do the same thing we did before. But, if you (or an administrator) will be adding one record at a time, it would be nice if the Title was auto-filled.

PreSaveAction() to the Rescue

And jQuery, of course…

Given the following NewForm.aspx for adding a new relationship:


New Item form with required site columns and non-required Title

We want to do two things with jQuery, so we don’t have to un-ghost the page:

  1. Hide the Title row – We’ll do this with jQuery instead of in the List settings, since we don’t want it to always be hidden; just here. Because we’re going to…
  2. Concatenate the choices in the site columns (Location/Department and Group) and save that string as the Title when the user clicks OK

Here’s a sneak peak at the jQuery, then I’ll explain it:

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
  <script src="../../../js/jquery.SPServices-0.4.8.min.js" type="text/javascript"></script>
  <script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $("input[title=Title]").parent().parent().parent().hide();
    });

    function PreSaveAction() {
        var txtDept = $("input[title=Location/Department]").val();
        var txtGroup = $("input[title=Group]").val();
        $("input[title=Title]").val(txtDept + ' - ' + txtGroup);
        return true;
    };
  </script>

Hiding the Title Row

The block inside $(document).ready(function() {}) runs as soon as the page is loaded ("ready"). Here’s the HTML from the ‘view source’ of the page to show what the page looks like when it’s loaded:

<TR>
    <TD nowrap="true" valign="top" width="190px" class="ms-formlabel"><H3 class="ms-standardheader">
        <nobr>Title</nobr>
    </H3></TD>
    <TD valign="top" class="ms-formbody" width="400px">
        <!-- FieldName="Title"
            FieldInternalName="Title"
            FieldType="SPFieldText"
        -->
        <span dir="none">
            <input name="ctl00$m$g_a689e4bb_2612_468b_b768_de131a929191$ctl00$ctl04$ctl00$ctl00$ctl00$ctl04$ctl00$ctl00$TextField" type="text" maxlength="255" id="ctl00_m_g_a689e4bb_2612_468b_b768_de131a929191_ctl00_ctl04_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField" title="Title" class="ms-long" /><br>
        </span>
    </TD>
</TR>

This is the entire row that we want to hide. The easiest way to find it is to look for the form field (or textbox) that is used to enter data. That’s the part in line 463: the <input … title="Title" /> tag. Notice the title attribute is set to the same thing as the H3 label in the left TD cell.

So, in jQuery, we say "find" like this: $("search criteria"). $("input[title=Title]"), then, means: "find the input tag that has a title attribute set to "Title" which is exactly what we’re looking for.

Now we traverse "up" or "out" of the nested HTML:

  1. We found the input tag, which is inside a span tag, so…
  2. .parent() is the span tag, which is inside a TD tag, so…
  3. .parent() is the TD tag, which is inside a TR tag, so…
  4. .parent() is the TR tag that we want to hide, so…
  5. .hide() hides it.


Title row is now hidden; we’ll set it programmatically before the save completes

Concatenating Fields for the Title

A few articles ago, we talked about the PreSaveAction() for use with the DVWP. In that case, we have to explicitly call it before a form action link is fired.

For a default (List Form Webpart) ghosted page, PreSaveAction() is called automatically when the OK button is clicked. That means, we just need to put code inside that function and SharePoint will process that before it submits the change to the database.

Just like with the Title control, we can find each of the other two boxes by searching for the input tag that has the appropriate title attribute set to the display name of the column.

So, for the first lookup control:

  1. $("input[title=Location/Department]") finds the control, and…
  2. .val() gives us the contents of the value attribute, which we…
  3. Store in the var we’re creating: txtDept

Repeat for the other control, storing the value in txtGroup

Now, we’ll find the Title control again:

  1. $("input[title=Title]"), but
  2. instead of getting its value, .val() sets the value attribute to
  3. txtDept + ‘ – ‘ + txtGroup

Since those two columns are required, both of them will have data or the page won’t save. But it won’t save until we set the Title.


Location/Department is set to Couriers, Group is set to Authorization Team. jQuery will concatenate these for the Title (hidden) before saving


The Title was set by jQuery

You could do something similar with the EditForm.aspx if you wanted, but it might be overkill, depending on how often changes will be made and how important it is that the Title always be exactly perfect.

Next time: We could have done this with a workflow, which we’ll do next time.

Author: Jim Bob Howard

Jim Bob Howard is a web designer / webmaster in the healthcare industry. He has been working with SharePoint since March 2009 and enjoys sharing what he has learned. He is a moderator and frequent contributor to Stump the Panel, and answers SharePoint questions on Twitter (@jbhoward) and via email ([email protected]).

View all entries in this series: Extending the DVWP»
Entries in this series:
  1. SharePoint: Extending the DVWP - Part 1: Layout Enhancement - Rearranging Columns - Default and Edit Templates
  2. SharePoint: Extending the DVWP - Part 2: Layout Enhancement - Rearranging Columns - Insert Template
  3. SharePoint: Extending the DVWP – Part 3: Getting it All on One Line - DVWP Function Action Links
  4. SharePoint: Extending the DVWP – Part 4: Turning DVWP Action Links into Buttons
  5. SharePoint: Extending the DVWP – Part 5: Doing Stuff Before Save on Submit - PreSaveAction()
  6. SharePoint: Extending the DVWP – Part 6: Examining the Form Action Links
  7. SharePoint: Extending the DVWP – Part 7: Creating a Form Action Workflow
  8. SharePoint: Extending the DVWP – Part 8: Creating a Form Action Workflow - The After Math
  9. SharePoint: Extending the DVWP – Part 9: Oops! Failed Setting Processor Stylesheet
  10. SharePoint: Extending the DVWP – Part 10: Passing Workflow Variables to a Form Action Workflow
  11. SharePoint: Extending the DVWP – Part 11: Getting More Form Fields to the Workflow
  12. SharePoint: Extending the DVWP – Part 12: Adding More Form Fields from the Data
  13. SharePoint: Extending the DVWP – Part 13: Putting PreSaveAction() to Work – Creating Variables
  14. SharePoint: Extending the DVWP – Part 14: Putting PreSaveAction() to Work with jQuery
  15. SharePoint: Extending the DVWP – Part 15: User-Managed Dropdowns with Site Columns
  16. SharePoint: Extending the DVWP – Part 16: User-Managed Dropdowns - Loading Data
  17. SharePoint: Extending the DVWP – Part 17: User-Managed Dropdowns – Creating a Relationship list
  18. SharePoint: Extending the DVWP – Part 18: User-Managed Dropdowns – Loading the Relationship list – Part 1
  19. SharePoint: Extending the DVWP – Part 19: User-Managed Dropdowns – Loading the Relationship list – Part 2
  20. SharePoint: Extending the DVWP – Part 20: Cascading Dropdowns - Applying the jQuery
  21. SharePoint: Extending the DVWP – Part 21: Cascading Dropdowns - Three-tier Cascade
  22. SharePoint: Extending the DVWP – Part 22: Creating Title Based on Other Fields with jQuery
  23. SharePoint: Extending the DVWP – Part 23: Creating Title Based on Other Fields with a Workflow
  24. SharePoint: Extending the DVWP – Part 24: A Note to Readers
  25. SharePoint: Extending the DVWP – Part 25: Using an Audit Trail by Creating List Items with SPServices
  26. SharePoint: Extending the DVWP – Part 26: Modifying the Edit Template
  27. SharePoint: Extending the DVWP – Part 27: Adding an Alternate Edit Template to a DVWP
  28. SharePoint: Extending the DVWP – Part 28: Massage the Remove Template
  29. SharePoint: Extending the DVWP – Part 29: Modifying Form Action Workflows on the remove Template
  30. SharePoint: Extending the DVWP – Part 30: Using EasyTabs with Filtered DVWPs to Make Data Manageable
  31. SharePoint: Extending the DVWP – Part 31: Filling in Default Data on the insert Template with jQuery
  32. SharePoint: Extending the DVWP – Part 32: Filling in Default Data on the insert Template with Multiple DVWPs
  33. SharePoint: Extending the DVWP – Part 33: Modifying Total and Subtotal Row Layouts in DVWP
  34. SharePoint: Extending the DVWP – Part 34: Using Icons for Form Action Links
  35. SharePoint: Extending the DVWP – Part 35: Putting it All Together
  36. SharePoint: Extending the DVWP – Bonus: Fixing the Insert Form Action When "No Matching Items"
  37. SharePoint: Extending the DVWP – Bonus: Creating a Title Based on Dropdowns with jQuery
 

Please Join the Discussion

16 Responses to “SharePoint: Extending the DVWP – Part 22: Creating Title Based on Other Fields with jQuery”
  1. Jim Bob:

    A shortcut to the containing TR for the Title’s INPUT element is to use the .closest() function instead of the set of .parent()s. .closest() simply traverses up the HTML tree until it hits a match. Much easier (and in some cases more reliable).

    M.

  2. Greg says:

    I can see this code snippet to be of great help incorporated to a ‘bulk’ edit form of sort.
    Rarely do users upload single documents to a library and you can’t really touch and modify the ‘Upload’ form. However, you can always pass a source redirect query string to a ‘Bulk Edit’ custom form after users have uploaded multiple items.
    Would this make sense?

    Greg

  3. Greg says:

    Jim Bob (and Marc if you peek in!),

    I have sort of a unique issue which I will briefly describe:
    – I have multiple lists – one being a ‘GeoList’ with Geographic information about 150+ projects (with adress, zip, Latitude and Longitude). The other lists are looking up to the GeoList via a unique project key. Thanks to SP2010, you can OOTB bring dynamically other fields from the same record
    I therefore have, in each of the ‘child’ lists, a look up to the GeoList and bringing multiple fields
    that I need – including Lat and Long field which are ‘numbers’ field in my GeoList.
    I do know how to create Aggregate DataSources using the DVWP – my restriction is that we are using the ESRI Mapping 3rd party webpart which is currently limited to using a single list as data source to create a map ‘layer’. 2nd restriction is that the Lat and Long fields must be numeric values for the webpart to ‘plot’ them.

    Here is where it blows – when you do a lookup field to a numeric field – the value type returned is text…

    I am therefore looking at creating hidden numeric fields and feeding dynamicaly values from the lookup fields. I am going to look at either workflows or jQuery but would appreciate some advice regarding the following questions:

    * I have to do lookups from the child list to the geolist anyway so I am thinking of bringing my looked up Lat and Long fields (returned as text) and do the conversion then – it keeps the workflow/ jQuery within a single list. However, I only need the workflow and/or jQuery to run when the Lat Long ‘original’ fields are either created or edited and then push the new values to the various child list. If I have the workflow/ jQuery on the ‘receiving’/ child lists side, I would have to run it more often that needed (do this make sense?)

    > should I have the workflow or jQuery initiation on the ‘parent’ list side or the child lists side? I think first option?

    * Lat and Long fields are numeric fileds with 6 decimals and I have 150 projects.
    I could have the code in the New and Edit forms but to be practical, users are going to populate or update them by either export/sync in Excel (via Excel 2007 addon) or in DataSheet view.

    I may have completely missed something in your series (which I am reading again), but is the DataSheet view something you can hook up some code. It is sort of a BulkEditCustom form question I guess…

    Thanks,Greg

  4. Greg says:

    Oh, did I mentioned that since I am using SP2010, I was wondering if – when ‘inline editing’ – there was a PreSave() action fopr the given row?
    Greg

  5. Brad says:

    What would be the syntax to access the controls in a dvwp?

    “So, for the first lookup control: $(”input[title=Location/Department]“) finds the control, and… ”

    The xsl has name of the id with the {$POS} appended, would be a way to have something like a for each loop?

    • The hard part about using the ID when it contains {$Pos} is that that variable basically comes out to a ‘_1′ or ‘_2′, etc. It probably wouldn’t give you very consistent results to search for an ID with that in it.

      I’m in Boston at SPTechCon, so I’ll need to take a look at this tonight after the sessions are over. I’ll think it through and see if I come up with something that will make a .each() work for all of the controls.

      Blessings,
      Jim Bob

  6. dc says:

    I have requirement to to fill a dropdwonlist on content editor webpart which data should come from a column of document library or list is there a way to do this with jquery i tried something like below but i m not getting where i m wrong.

    $(document).ready(function() {
    var soapEnv =” doclist “;
    $.ajax({url: window.location.protocol+”//”+window.location.hostname+”:”+port+L_Menu_BaseUrl+”/_vti_bin/lists.asmx”;type: “POST”,dataType: “xml”,data: soapEnv,complete: processResult,contentType: “text/xml; charset=”utf-8″”});});

    function processResult(xData, status) {
    $(xData.responseXML).find(”z\:row”).each(function() {
    $(’#mydropdown’).
    append($(”").
    attr(”value”,$(this).attr(”ows_Title”)).
    text($(this).attr(”ows_Title”)));
    });
    };

    Thanks In advance.

Trackbacks

Check out what others are saying about this post...
  1. [...] superfluous. It just tells us what data is in the relationship columns. We can let SharePoint fill that data in for us with jQuery. Alternately, we could fire up a workflow to do it [...]

  2. [...] This question came in my email from Fernando: I used the code from your article, Extending the DVWP – Part 22: Creating Title Based on Other Fields in jQuery. [...]




Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!