views:

228

answers:

2

I'm new a jQuery. I have gotten validate to work with my form (MVC 1.0 / C#) with this:

      <script type="text/javascript">
      if (document.forms.length > 0) { document.forms[0].id = "PageForm"; document.forms[0].name = "PageForm"; }
      $(document).ready(function() {
          $("#PageForm").validate({
              rules: {
                  SigP: { required: true }
              },
              messages: {
                  SigP: "<font color='red'><b>A Sig Value is required. </b></font>"
              }
          });

      });
  </script>

I also want to hide the Submit button to prevent twitchy mouse syndrome from causing duplicate entry before the controller completes and redirects (I'm using an GPR pattern). The following works for this purpose:

  <script type="text/javascript">  
  //
  // prevent double-click on submit
  //
      jQuery('input[type=submit]').click(function() {
          if (jQuery.data(this, 'clicked')) {
              return false;
          }
          else {
              jQuery.data(this, 'clicked', true);
              return true;
          }
      });
  </script>

However, I can't get the two to work together. Specifically, if validate fails after the Submit button is clicked (which happens given how the form works), then I can't get the form submitted again unless I do a browser refresh that resets the 'clicked' property.

How can I rewrite the second method above to not set the clicked property unless the form validates?

Thx.

A: 

If you're using this validation plugin, it comes with a valid() method.

  jQuery('input[type=submit]').click(function() {
      var self = $(this);

      if (self.data('clicked')) {
          return false;
      } else if (self.closest('form').valid()) {
          self.data('clicked', true);

          return true;
      };
  });

or even:

  jQuery('input[type=submit]').click(function(event) {
      var self = $(this);   

      if (self.closest('form').valid()) {
          self.attr('disabled', true);
      };
  });
Matt
A: 

I would do it like this:

$('#PageForm').submit(function() {
   if($(this).valid()) $(':submit', this).attr('disabled', true);
});

This is triggered on submit of the form, looks for any submit button inside and disables it if the form was valid.

Use $('#PageForm :submit').removeAttr('disabled'); to re-enable the button when ready.

Nick Craver