Validate a form on a click (pun intended)

I have a grid with users, where for each user several reports can be generated.

The reports must have a start and end date and because some technical constraints and because I wanted to let users re-use an url, I decided to send the values by query string.

Then, I had to add some validation, so that the user would be forced to select the report dates.

Then, the problem, how to prevent the click on the link if the form was not valid?

Here’s the solution:

 

<div id="start-date-area">
    <p>Select the start date:</p>
    <input id="cal-from-date" name="from" type="text" class="required for-report clickable" readonly="readonly" />
    <p></p>
</div>
<div id="end-date-area">
    <p>Select the end date:</p>
    <input id="cal-to-date" name="to" type="text" class="required for-report clickable" readonly="readonly" />
    <p></p>
</div>

 

$("a.submit").live("click", function(ev)
{
    ev.preventDefault();
    var $self = $(this);

    $("#aspnetForm").validate();
    if ($("#aspnetForm").valid())
    {
        // generate a querystring fragment from the fields I need to send to the server
        var qs = $(".for-report").serialize();

        //console.log("qs: " + qs);
        document.location = $self.attr("href") + "&" + qs;
    }
});

I have used $("a.submit").live("click", function(ev) instead of

$("a.submit").click(function(ev) because the rows are added in the grid using ajax and click works only on current elements and not on possible future elements.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s