Thursday, February 9, 2012

Re-enabling Form Fields and Form Validation

In my last post I showed you how to disable form fields and controls like the Submit button.

Well, that's not going to do you much good unless you can re-enable the button and submit the form. Using a little more jQuery, here's how to peform a little form validation and do just that.

Notice the field "Requested Tickets?" It's the only field on the form that you can actually modify. I'm going to attach some form validation to this field to make sure the user doesn't enter an invalid quantity.

If you'll notice, underneath the text "Requested Tickets" it tells you how many tickets are available- 4. (How I got this there is the subject of another post.) If the user requests 10 tickets then the form should (politely) let them know that it's not going to happen and the Submit button should stay disabled.

But if the user requests four or less tickets, then all should be right with the world and they should be allowed to submit their request.

To place validation on the "Requested Tickets" field, go into SPD and add an ID to the SharePoint:FormField's parent td. Something like id="tktsReq" should do.

BTW- Sometimes, SPD likes to add the mysterious {generate-id()} to ID fields that you add on your own. See Marc Anderson's blog post on how to get around this.

Now, go back to your content editor web part and add the following function to your script

function checkTktReq(){
var tktsAvailable = $("input[title='Available']").val(); // value taken from a hidden form field
var tktsRequested = $("input[title='Requested Tickets']").val();
if(tktsAvailable<tktsRequested){
$('#btnSubmit :input').attr('disabled','disabled');
$('.disableMe :input').attr('disabled','disabled');
alert('There are only ' +tktsAvailable+ ' tickets available for this event and you have asked for '+tktsRequested+'. Please modify the number of tickets you are requesting.' );
} else {
// Re-enable the Submit button
$('#btnSubmit :input').removeAttr('disabled');
// Re-enable the form fields. Otherwise, you'll get an error.
$('.disableMe :input').removeAttr('disabled');
}
}

and to the $(document).ready function, add...
$("#tktsReq").keyup(checkTktReq);

This little piece is going to listen for changes to the Ticket Request field and call the function checkTktReq() which compares the value entered to the number of tickets available and responds accordingly. You don't have to use the "keyup" event. You could use change, keydown, or a variety of others. Feel free to use whatever works best for your purposes.

So let's see it in action!
If there are 4 tickets available and I ask for 22 I get a nice error message and the form remains disabled.


But, if I ask for only 2 tickets, the value is valid and the submit button is re-enabled.


I hope this helps!

CG

No comments: