Here’s a question I got in the forums at the USPJ Academy today. It’s a nice simple question, but the answer points out a cool thing about SharePoint forms: the PreSaveAction.
I was watching the excellent video posted by Marc Anderson: Enhancing the User Experience with jQuery – Chaining from Selector.mp4. In this video Marc runs through some interesting scenarios, which I tried on my own. The following scenario gave me issues: Required field that has either a disabled or hidden control that is prefilled. The problem is that when I hit OK or Save, the form never sees the pre-filled value. e.g. Simple text field (Say the out-of-the-box Title field.) Let’s pre-fill with “Hello World” and disable the field. The words “Hello World” do show up, but I am not allowed to save the form by clicking on OK. Any thoughts?
If you want to watch that “excellent video”, you’ll have to become a student at the Academy! However, this is a really good question. When an element in a form is disabled, its value effectively won’t be submitted along with the form. If the column is required, like is the case with the Title column, then when you submit the form you’ll get the validation error:
You need to do a little sleight of hand to make this work. Here’s a little example:
So when the document is ready, you can set the Title column’s value to ‘Hello World’, and then disable the column as in the example above.
The trick is to re-enable it when the form is submitted using the PreSaveAction. You can read more about the PreSaveAction in my blog post Validation on SharePoint Forms – Part Four (and others), but the basic idea is that the PreSaveAction is a function stub that SharePoint always calls on a form submit. If you want to do some additional things, like your own validations, this is where you put them. By re-enabling the Title column, your form will submit just fine.
Note that if you want the form to submit, you return true from the PreSaveAction. If you don’t want the form to submit, then you’d return false. So, for instance, if you are checking to see if a Start Date is before the End Date for an Event and it isn’t, you’d probably put a validation error message into the DOM and return false. This keeps the form from submitting, forcing the user to fix the issue.
As noted in one of my replies to the comments below, this is an old post, and jQuery has moved forward a bit. Depending on what version you are using, the line:
may not work. You may instead need to use:
See the jQuery documentation for .prop().