Search code examples
javascriptjqueryjquery-validation-engine

Validate form through <a> tag click


I am currently working with jquery validation and forms. I came across a great plugin HERE which so far works perfectly. I am running into a wall since I have a form split into sections inside jquery tabs. I have placed in these tabs <a> tags that act as buttons Next and Previous. Instead of clicking submit to validate, I would like to validate the fields when clicking Next or Provious. I have tried binding to on click validate but I get no result. How can I validate the form by clicking on an <a> tag? Here is a mockup Example

//jquery tabs- Next and Previous
<script>
    $(function() {

        var $tabs = $('#tabs').tabs();

        $(".ui-tabs-panel").each(function(i){

          var totalSize = $(".ui-tabs-panel").size() - 1;

          if (i != totalSize) {
              next = i + 2;
              $(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page &#187;</a>");
          }

          if (i != 0) {
              prev = i;
              $(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>&#171; Prev Page</a>");
          }

        });

        $('.next-tab, .prev-tab').click(function() { 
               $tabs.tabs('select', $(this).attr("rel"));
               return false;
           });


    });
</script>

//Jquery Validation
<script>
    jQuery(document).ready(function(){
        // binds form submission and fields to the validation engine
        jQuery("#formID").validationEngine();
    });

    function checkHELLO(field, rules, i, options){
        if (field.val() != "HELLO") {
            // this allows to use i18 for the error msgs
            return options.allrules.validate2fields.alertText;
        }
    }
</script>

//Jquery Bind <a> to validate 
<script>
$(document).ready(function() {
     $("form").validate();
     $("a").bind("click", function() { alert($("form").valid()); });
});
</script>

HTML

<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
            <form id="formID" class="formular" method="post">
            <span>Name:</span><br>
            <input value="" class="validate[required] text-input" type="text" name="req" id="req" />    
            <label>
                <span>Favorite sport 2:</span>
                <select name="sport2" id="sport2" multiple class="validate[required]">
                    <option value="">Choose a sport</option>
                    <option value="option1">Tennis</option>
                    <option value="option2">Football</option>
                    <option value="option3">Golf</option>
                </select>
            </label>
            </form>           
</div>

Solution

  • You're dynamically adding <a> tags so you'll need to use live() on() (live is deprecated, thanks jbabey), as opposed to bind.

    That way, any matching elements now or added in future will be properly bound.