Friday, May 14, 2010

Required field using jQuery in Newform and EditForm

Hi All,

May times there are requirements like we need to define a field as a required field in SharePoint. Yes, you will say what is new with that? This is built in feature of SharePoint.

Ok, what if I say that field should be mandatory while updating list item but not while inserting the list item. What if I say if value of one drop down in xyz, abc field becomes mandatory?

Well, in scenarios like this we can use jQuery. Yes, jQuery is the answer to this question. Let us put this in to a real scenario.

Ok, before getting into this, I would like to share some steps about this. First we need to handle the change event of drop down. Then we will check the value of the drop down, if the value is suspended, we will pop up one message saying that now because you have selected Suspend status, you must mention the reason for this and we will disable the button OK. We have to do this because there is no way we can stop user clicking ok button unless user writes the reason. Otherwise item will be updated which we do not want.

we also need to handle lost focus event of text area, and at the end we will count the number of characters in the text area. If total comes to zero, well then keep button disabled. If it is not zero and more than zero, then we will enable the button.

Or else we can ask user to select Status back to value which was earlier and enable the button.

Yes, this all steps are required. Try for yourself and you will realize that yes these all steps are required. It may look like some lengthy solution, But remember we did all this stuff right on browser. We never went to write down the code in event handler (this stuff really annoy the end user, as it takes to a different error page, or creating any custom field for this. This is what we wanted and this is the power of jQuery. Isn’t it.

Ok, let us see now in practical

First add the content editor web part above the New Form or Edit Form LVWP where ever you want to place the logic.

This is the layout of my editform.



Add the following code to the content editor web part. Do not forget to reference appropriate jquery file from your library.

<script type="text/javascript" src="{site URL}/Shared%20Documents/jquery-latest.js">
</script>


$(document).ready(function() {
//Below function makes sure that if the status is not suspended in edit mode, it disables the reason text //area
var text = $("select[title$='Status'] :selected").text();
if(text != "Suspended")
{
$("textarea[title$='Reason'] ").attr('disabled', true);

}


Below function makes sure that when the status drop down is changed to suspended status, reason textarea becomes enabling to write down the result and disabled the OK button unless user enters the reason. If suspend is not selected, again disable the reason field and enable the OK button.

$("select[title$='Status']").change(function()
{

var text = $("select[title$='Status'] :selected").text();

if(text == "Suspended")
{
alert('you must provide reason for suspending this order');
$("input[value$='OK']").attr('disabled', true);
$("textarea[title$='Reason'] ").attr('disabled', false);
}
else
{
$("input[value$='OK']").attr('disabled', false);
$("textarea[title$='Reason'] ").attr('disabled', true);
}

});


Finally below is the blur event of the reason field, which checks if anything is entered in reason field or not. If not keep the button OK disabled, or else if something is written enable the button.

$("textarea[title$='Reason']").blur(function()
{

var text = $("textarea[title$='Reason'] ").text();

if(text.length <= 0)
{
$("input[value$='OK']").attr('disabled', true);
}
else
{
$("input[value$='OK']").attr('disabled', false);
}


});

});

</script>


So here is the result of it.

See below image as status is not suspended I am not able to type in anything in reason field.



Below figure shows when I changed the status to Suspended, it pops up message and disabled the ok button after message is displayed.






After mentioning the reason, OK button enables.



That is it. You have just made required field validation without using any custom field or writing event handler.

31 comments:

$!m said...

Hello, I am trying to do something similar.
i have 5 fields which take in a Number and I need to put in a check that atleast one of them should have a numeric value.
I have been trying to modify it, but i'm stuck.
Please help me.

Thanks

SharePoint Kings said...

Sim,

try for one field first.
if it is working for one field then it should work for 5 fields also.

and alert each value you got, that's the best way to debug javascript

Unknown said...

The post seems pretty good and useful, but when i tried implementing it for my case it aint working.

The .change function is not working precisely for me, everything works in document.ready, but when i do .change for a specific dropdown it doesnt.

Suggest something.

SharePoint Kings said...

Chinmay,

.change is the selected change event of dropdown (select/option in html)

you can check the use of change function of jquery form below link

http://api.jquery.com/change/

if you jquery is firing then you just have to adjust it as per you requirement.

in our case we are firing .change event on status dropdown may be you don't have dropdown with same name so may be that's why your event not firing.

Reggie said...

I am trying to get this to work, but I am having issues. Sharepoint will not allow me to add a CEWP in the new item form or edit form. where do i put the code?

SharePoint Kings said...

Reggie,

check this link
http://www.sharepointkings.com/2008/05/how-to-edit-list-forms-like-newformaspx.html

Reggie said...

The text area count function is not working for me any clue why? I have sharepoint 3.0 and designer 2007

SharePoint Kings said...

Reggie,

it might be name change so you might not be getting object.

place alert after few line and found what the exact problem you are getting.

view source will help you to get object.

Reggie said...

Thanks. The orginal works, but you will have to keep it in plain text. I had rich text.

Reggie said...

What if i want to use radio buttons? How do i read the val of a radio button and do a onchange event?

SharePoint Kings said...

Reggie,

check how it renders in view source. and find on net how to get that object in javascript

Pradeep (pradeep1701@gmail.com) said...

I am looking for a similar functionality. However, I would need to make a field (Closure Date) as * required when the user selects "Closed" choice under the Status column.

SharePoint Kings said...

pradeep,

you can achieve this by modifying the javascript.

just put alerts between the script
check the value to "Close" and then apply javascript on ok which will return with alert.

Unknown said...

Hi,
This is working great, except for the fact that the OK button will not become enabled after the text field I'm using is populated. Any ideas why?

Thank you in advance,
Caroline

SharePoint Kings said...

choff,

if you see this code in the post

$("textarea[title$='Reason']").blur(function()
{...});

then it fires blur event of the field "Reason" which is text area (multi-line render as text area) if you have single line text box then use input and use find control using title

that might be the problem.

put alert on blur or change event of you control so that u can figure out when it fires and what's the problem

Unknown said...

Thank you very much, I did end up figuring it out, I had been using the internal title of the field rather than the display.

I do have another question however, any ideas on how to get this to work for a people picker or date field?

Thank you!

SharePoint Kings said...

choff,

we had not tried with people picker but if you check people picker is rendered as a text box + image for lookup so you can tried to find that text box and give it a try.

if you are able to do that please share that with us also

Thanks

Unknown said...

Hi,

I actually figured out how to make this work with the people picker and date field. For the people picker I opened the source and found where the div section contains contentEditable="True" and chose the id that ended in UserField_upLeveldiv, so it looks like this: $("div[id$='(paste id that ends in _UserField_upLeveldiv'] ").attr('disabled', false);

For the date field in the source I found the id in the input tag that ends in DateTimeField_DateTimeFieldDate, so the format looks like this:
$("input[id$='(paste id that ends in_DateTimeField_DateTimeFieldDate] ").attr('disabled', false);
I hope that helps!

Thank you!

SharePoint Kings said...

thanks choff,
thanks for sharing, that helps a lot to everyone.

Unknown said...

Hi How did you find the ID of dateTime type column? I could not find it from the editform.aspx solurce.
can you please help me with this.

SharePoint Kings said...

Puja,
yes it will not work directly for datetime control as datetime is it self is combination of multiple control like textbox and image

so for that you have to find textbox (search title or ID of that from view source) and check your validation.

Anonymous said...

For those who are looking for an alternative way to achieve custom validation can do so by adding a PreSaveAction() javascript function. This function will get called when a user clicks save/ok button. Here you can do all sorts of validation.
Just google it and you will get enough examples (especially around start/end date validation).

Anonymous said...

Hi,

But a user will still be able to enter the data via datasheet view and ignore the validation. Any way to have the same validation applicable with datasheet view also?

Thanks

SharePoint Kings said...

Anonymous,
yes this method will not be applicable in datasheet view.

mmandel said...

I'm trying to get something like this to work using the strange Content Type dropdown field that appears when you have more than one content ype in a list. My problem seems to be in specifying that Content Type field in the javascript.

At this point, I simply want to be able to grab the selected value in that column, but so far haven't been able to.

I've tried both of the following to specify the field (and later to show an alert with the selected value):

var text = $("select[title$='Content Type'] :selected").text();

var text = $("select[id*='ContentTypeChoice'] :selected").text();

but neither works. "Content Type" is the title of the field. I've also tried [title$='Content_x0020_Type'] in case the space is the problem, but that doesn't fix it.

Anonymous said...

Thanks for writing excellent blog, it is perfectly working in my case.
Just having a small issue while using Reason field's output as Rich Text or Enhanced Text it is not working.
Can you let us how can we modify the script to work in case of Rich or Enhanced Text.
Thanks again

SharePoint Kings said...

@mmandel,
you must check view source of the page and see what is the ID if that dropdown in HTML. also you can use IEDeveloperTool (F12 in IE8+) to find out ID if specific element.

once you have proper pattern of id then you can use it in your JavaScript.

SharePoint Kings said...

@anonymous, check this out http://www.sharepointkings.com/2010/10/getting-sharepoint-rich-text-field-data.html

this will help you to get rich field content in JavaScript.

Roshan Tated said...

Hi,

I am trying to deploy this on my Edit.aspx page. But being a novice to Sharpoint, I do not have idea about where to upload this Jquery file and what its contents should be like.

Can you please elaborate on the Jquery file?

Thanks in advance,
Roshan.

Roshan Tated said...

Hi,

The post seems to be pretty useful.
I am trying to deploy this on Edit.aspx page. just one query as to where do we need to put this Jquery file and what should be the contents of this file.

Being a novice to sharepoint, I do not have any idea about the Jquery.

Thanks in advance,
Roshan.

SharePoint Kings said...

@Roshan Tated,

you can upload JQuery file to any of you document library and take reference of it or you can put it in templates/layout folder of 14 hive so it will be available globally. either way is fine.

we usually like to put it in layouts folder if we have permission and access to server.




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