Friday, September 14, 2012

how to hack jQuery form validations into SharePoint

The button that would allow you to submit a SharePoint form looks like this:

<input type="button" name="ctl00$m$g_426ced44_2eea_4b90_82e1_f6efc8dcc7f2$ctl00$toolBarTbltop$RightRptControls$ctl01$ctl00$diidIOSaveItem" value="Save" onclick="if (!PreSaveItem()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$m$g_426ced44_2eea_4b90_82e1_f6efc8dcc7f2$ctl00$toolBarTbltop$RightRptControls$ctl01$ctl00$diidIOSaveItem", "", true, "", "", false, true))" id="ctl00_m_g_426ced44_2eea_4b90_82e1_f6efc8dcc7f2_ctl00_toolBarTbltop_RightRptControls_ctl01_ctl00_diidIOSaveItem" accesskey="O" class="ms-ButtonHeightWidth" target="_self" />

 
 

As you can see:

  1. The form does not submit upon a press of the enter key, only upon a click of the button.
  2. ctl00$m$g_426ced44_2eea_4b90_82e1_f6efc8dcc7f2$ctl00 and a lot of other noise is very likely subject to change from deploy to deploy and should not be depended upon and copied elsewhere.
  3. It will be a dirty hack to make this button do more than what it is made to do.

 
 

Let's say I want to roll my own jQuery-based form validation. Why, might I want to do so? Because some fields may be conditionally hidden while required if not hidden. (see: this) But how may I keep the button from submitting if validation requirements are not met? Great question. I have decided to hide the button, put my own save button on the form, and have my save button click the real (hidden) save button if validation requirements are met like so:

var savebutton = $(".ms-formtoolbar:first").find('input:first');
savebutton.click();

 
 

I have "moved" the ability to submit the form out of SharePoint's JavaScript into my own jQuery in this means. My own jQuery will be a lot easier to refactor.

2 comments:

  1. You can also add your logic into the PreSaveAction() and stick with SharePoint's default button.

    M.

    ReplyDelete
    Replies
    1. Thanks. Sounds like that may be the better way to go. I'll investigate.

      Delete