I have a straight forward form sprinkled with a bit of jQuery, but I have a small issue. When I hit Next button it goes to the next step without popping up the small field with "you have to complete this required field". How can I force the next button to do this action as the submit button does it by default? If someone could show me an elegant way to adapt this to my curent code I would apreeciate it a lot :)

<!DOCTYPE html>
 <html lang="en">
 <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <style type="text/css">
    #regiration_form fieldset:not(:first-of-type) {
        display: none;
    }
  </style>
  <title>Form</title>
</head>
<body>
  <div class="container">
    <h1></h1>
    <div class="progress">
        <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
    </div>

    <form id="regiration_form" action="action.php"  method="post">
    <fieldset>
        <h2>Step 1: Create your account</h2>
        <div class="form-group">
        <label for="email">Email addresss</label>
        <input type="email" class="form-control" id="email" name="data[email]" placeholder="Email" required>
      </div>
      <div class="form-group">
        <label for="exampleInputPassword1">Password</label>
        <input type="password" class="form-control" id="password" placeholder="Password" required>
      </div>
        <input type="button" name="data[password]" class="next btn btn-info" value="Next" />
    </fieldset>
    <fieldset>
        <h2> Step 2: Add Personnel Details</h2>
        <div class="form-group">
        <label for="NameA">First Name</label>
        <input type="text" class="form-control" name="data[NameA]" id="NameA" placeholder="First Name" required>
      </div>
      <div class="form-group">
        <label for="NameB">Last Name</label>
        <input type="text" class="form-control" name="data[NameB]" id="NameB" placeholder="Last Name" required>
      </div>
        <input type="button" name="previous" class="previous btn btn-default" value="Previous" />
        <input type="button" name="next" class="next btn btn-info" value="Next" />
    </fieldset>
    <fieldset>
        <h2>Step 3: Contact Information</h2>
        <div class="form-group">
        <label for="mob">Mobile Number</label>
        <input type="text" class="form-control" id="mob" name="data[mob]" placeholder="Mobile Number" required>
      </div>
      <div class="form-group">
        <label for="address">Address</label>
        <textarea  class="form-control" name="data[address]" placeholder="Communication Address" required></textarea>
      </div>
        <input type="button" name="previous" class="previous btn btn-default" value="Previous" />
        <input type="submit" name="submit" class="submit btn btn-success" value="Submit" id="submit_data" />
    </fieldset>
    </form>
  </div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
    var current = 1,current_step,next_step,steps;
    steps = $("fieldset").length;
    $(".next").click(function(){
        current_step = $(this).parent();
        next_step = $(this).parent().next();
        next_step.show();
        current_step.hide();
        setProgressBar(++current);
    });
    $(".previous").click(function(){
        current_step = $(this).parent();
        next_step = $(this).parent().prev();
        next_step.show();
        current_step.hide();
        setProgressBar(--current);
    });
    setProgressBar(current);
    // Change progress bar action
    function setProgressBar(curStep){
        var percent = parseFloat(100 / steps) * curStep;
        percent = percent.toFixed();
        $(".progress-bar")
            .css("width",percent+"%")
            .html(percent+"%");     
    }
});
</script>

Dani AI

Generated

You are seeing that because the Next buttons are plain type="button". Native HTML5 messages only appear on submit, or when you explicitly ask the browser to validate. The fix is to validate just the current step before you advance, and only move on if all fields in that step pass.

Drop this helper in your script and use it in your .next click handler:

function canAdvance($fieldset) {
  // Only check inputs in the current step
  var $inputs = $fieldset.find(":input").filter(function () {
    // ignore buttons and disabled fields
    return this.willValidate && this.type !== "button" && this.type !== "reset";
  });
  for (var i = 0; i < $inputs.length; i++) {
    var el = $inputs[i];
    if (!el.checkValidity()) {
      if (typeof el.reportValidity === "function") {
        el.reportValidity(); // show the native bubble
      } else {
        el.focus(); // basic fallback
      }
      return false; // block Next
    }
  }
  return true;
}

$(".next").on("click", function () {
  var $fs = $(this).closest("fieldset");
  if (!canAdvance($fs)) return;
  // your existing show/hide + progress code here
});

A couple of quick cleanups while you are here:

  • In Step 1, the password <input> is missing a name and the Next button has name="data[password]". Move that name onto the password input and remove it from the button, otherwise the password will never be posted.
  • Stick with .closest("fieldset") rather than .parent() so the code is resilient to markup changes.

If you prefer a plugin route like @Haji Sameon suggested, add novalidate on the <form> to suppress native bubbles and let the plugin show its own messages. Also ensure each field that needs validation has a name attribute, which the plugin relies on.

Recommended Answers

All 2 Replies

Anyone?

Well, im having the same problem like you before, but i found this validation for my html page:

js file (register.js):

// JavaScript Validation For Registration Page

$('document').ready(function()
{        
         $("#YourFromName").validate({

          rules:
          {
                YourFieldName1: {
                    required: true
                },  
           },
           messages:
           {

                YourFieldName1: {
                      required: "Validation messages here.."    
                      },

           },
           errorPlacement : function(error, element) {
              $(element).closest('.form-group').find('.help-block').html(error.html());
           },
           highlight : function(element) {
              $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
           },
           unhighlight: function(element, errorClass, validClass) {
              $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
              $(element).closest('.form-group').find('.help-block').html('');
           },

           }); 
    })

page1 (html file):

<html lang="en">
<head></head>
<body>

<section id="container" class="">
    <section id="main-content">
        <section class="wrapper site-min-height">
            <!-- page start-->
            <div class="row">
                <div class="col-lg-12">
                    <section class="panel">
                        <section class="panel-body">
                            <div class="form">
                                <section class="panel">
                                    <hr class="myhr">
                                </section>
                                <form action="NextPage.php" method="post" name="YourFromName" id="YourFromName" class="form-horizontal" novalidate>
                                    <div class="form-group">
                                        <label class="col-sm-2 col-sm-2 control-label">YourFieldName1</label>
                                        <div class="col-sm-10">
                                             <select class="form-control m-bot15" id="YourFieldName1" name="YourFieldName1" required="required">
                                                <option value="">--Choose--</option>
                                                <option value=""></option>
                                             </select>
                                             <span class="help-block" id="error"></span>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label class="col-sm-2 col-sm-2 control-label"></label>
                                        <div class="col-sm-10" style="text-align: right">
                                        <button type="submit" name="save" id="save" class="btn btn-primary" >Save </button>
                                        <button type="reset" name="reset" id="reset" class="btn btn-primary">Reset</button>
                                        <input type="button" name="btnBack" id="btnBack"  value="Back" class="btn btn-primary"> 
                                        </div> 
                                    </div>
                                </form>

                            </div>
                        </section>
                    </section>
                </div>
            </div>
        </section>
    </section>
    <?php include_once("footer.php") ?>
</section>

<script src="jquery.js"></script>
<script src="bootstrap.min.js"></script>
<script src="jquery.validate.min.js" ></script>
<script src="register.js" ></script>
</body>
</html>

Hope this can help u a bit :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.