Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery validation with "button" type rather than "submit" type for a form

$('selector').validation() seems to be built more for the "input" type button than the "button" type. How would I get it working with a button type within the form?

@using(Html.BeginForm(new {id="TheForm"}))
{
     // code here
     <input id="TheButton" type="button">
}

JQuery:

$(document).ready(function() {
      $("#TheForm").validate({
            rules: {
                 "AuditDoc.Title": {
                       required: true
                  }
            }
      });
      $("#TheButton").click(function() {

      });
});

Using this basic idea, how would I get jquery validate working with a button rather than a submit type button? I've seen examples where JQuery automatically displays error messages when the rules aren't met using submit type, but it doesn't appear to work with button type. I'd appreciate any advice!

like image 768
TheDude Avatar asked Aug 11 '12 12:08

TheDude


4 Answers

$(document).ready(function () {
        $("#TheForm").validate({
            rules: {
                "AuditDoc.Title": {
                    required: true
                }
            }
        });

        $("#TheButton").click(function () {
            if (!$("#TheForm").validate()) { // Not Valid
                return false;
            } else {
                $("#TheForm").submit()
            }
        });

        $('#btnReset').live('click', function (e) {
            //var $validateObj = $('#formId');
            //Or
            var $validateObj = $(this).parents('form');

            $validateObj.find("[data-valmsg-summary=true]").removeClass("validation-summary-errors").addClass("validation-summary-valid").find("ul").empty();
            $validateObj.find("[data-valmsg-replace]").removeClass("field-validation-error").addClass("field-validation-valid").empty();
        });
    });
like image 74
Thulasiram Avatar answered Nov 14 '22 00:11

Thulasiram


$(document).ready(function(){

     $("#myform").validate();
     $("#byuttion").click(function() {

       if($("#myform").valid())
       {
          $("#myform").submit();
       }
       else 
      {
          return false;
      }

      });

});
like image 34
Kanishka Panamaldeniya Avatar answered Nov 13 '22 23:11

Kanishka Panamaldeniya


One hackish way could be:

$("#TheButton").click(function() {
     $("#TheForm").submit()
});
like image 4
Rafay Avatar answered Nov 14 '22 00:11

Rafay


It works pretty much the same as it would with a normal input except it doesn't support the submit method. preventDefault just stops the page from doing it's default request.

$("#TheButton").click(function(event) {
    event.preventDefault(); //or return false
    getData();
});
like image 3
Josh Bedo Avatar answered Nov 14 '22 01:11

Josh Bedo