Parsley.js - 所有表单的一个多步骤函数

时间:2015-06-21 12:14:42

标签: javascript jquery forms parsley.js

我正在尝试使用Parsely.js验证插件设置多步骤表单验证。

我按照这里的文档:“http://parsleyjs.org/doc/examples/multisteps.html” - 但唯一的问题是我将会有很少的表单在网站上有多个步骤,在某些页面上会有多个表单。

提供的代码段一次只支持一个表单,我需要为每个表单指定一个ID,如下所示:

<script type="text/javascript">
$(document).ready(function () {
  $('.next').on('click', function () {
    var current = $(this).data('currentBlock'),
      next = $(this).data('nextBlock');

    // only validate going forward. If current group is invalid, do not go further
    // .parsley().validate() returns validation result AND show errors
    if (next > current)
      if (false === $('#demo-form').parsley().validate('block' + current))
        return;

    // validation was ok. We can go on next step.
    $('.block' + current)
      .removeClass('show')
      .addClass('hidden');

    $('.block' + next)
      .removeClass('hidden')
      .addClass('show');

  });
});
</script>

有没有办法调整代码段,以便自动检测表单是否有多个步骤并相应地应用相应的行为/设置?而不是必须为每个表单反复复制该代码段。

以下是HTML的外观:

<form id="demo-form" data-parsley-validate>
  <div class="first block1 show">
    <label for="firstname">Firstname:</label>
    <input type="text" name="firstname" data-parsley-group="block1" required/>

    <label for="lastname">Lastname:</label>
    <input type="text" name="lastname" data-parsley-group="block1" required />
    <span class="next btn btn-info pull-right" data-current-block="1" data-next-block="2">Next ></span>
  </div>

  <div class="second block2 hidden">
    <label for="fullname">Email:</label>
    <input type="text" name="fullname" required  data-parsley-type="email" data-parsley-group="block2" />
    <span class="next btn btn-info pull-left" data-current-block="2" data-next-block="1">< Previous</span>
    <input type="submit" class="btn btn-default pull-right" />
  </div>
</form>

1 个答案:

答案 0 :(得分:2)

您需要更改代码以指定用户当前使用的表单。我已经更改了您用来执行此操作的代码块,包括以下注释:

$(document).ready(function () {
  $('.next').on('click', function () {
    // Find the form whose button was just clicked
    var currentForm = $(this).parents('form').first();

    var current = $(this).data('currentBlock'),
    next = $(this).data('nextBlock');

    // only validate going forward. If current group is invalid, do not go further
    // .parsley().validate() returns validation result AND show errors
    if (next > current)
      // Use currentForm found above here, rather than hard coded form id
      if (false === currentForm.parsley().validate('block' + current))
        return;

    // validation was ok. We can go on next step.
    // Hide current block on current form
    currentForm.find('.block' + current)
      .removeClass('show')
      .addClass('hidden');

    // Show next block on current form
    currentForm.find('.block' + next)
      .removeClass('hidden')
      .addClass('show');
  });
});