使用bootstrap nav-pill单击“下一步”按钮进行表单验证

时间:2018-02-02 10:35:38

标签: javascript php jquery twitter-bootstrap

我正在使用nav-pill里面有一个表单,并将其分成每个部分,例如作为入场详情,个人详细信息,家庭详细信息,每个步骤都有“下一步”按钮,最后保存按钮{{ 1}}。

nav-pill
$('.btnNext').click(function() {
  $('.nav-pills > .active').next('li').find('a').trigger('click');
});

$('.btnPrevious').click(function() {
  $('.nav-pills > .active').prev('li').find('a').trigger('click');
});

//  Bind the event handler to the "submit" JavaScript event
$('#validateFirst').click(function() {

  // Get the Login Name value and trim it
  var name = $.trim($('#admission_no').val());

  // Check if empty or not
  if (name === '') {
    alert('Admission No. field is empty.');
    return false;
  }
});

我尝试使用按钮点击功能,同时单击“下一步”按钮,如:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<ul class="nav nav-pills nav_content">
  <li class="active"><a data-toggle="pill" href="#admission">Admission Details</a></li>
  <li><a data-toggle="pill" href="#personal">Personal Details</a></li>
  <li><a data-toggle="pill" href="#family">Family Details</a></li>
</ul>

<form id="form1" action="<?php echo site_url('student/create') ?>" id="employeeform" name="employeeform" method="post" accept-charset="utf-8" enctype="multipart/form-data">
  <div class="tab-content">
    <div id="admission" class="tab-pane fade in active">
      <div class="row">
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Admission Number *</label>
            <input id="admission_no" name="admission_no" placeholder="" type="text" class="form-control" value="admission_no" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Application Number  *</label>
            <input id="application_no" name="application_no" placeholder="" type="text" class="form-control" value="application_no" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Academic Year  *</label>
            <input id="academic_year" name="academic_year" placeholder="" type="text" class="form-control" value="academic_year" />
          </div>
        </div>
      </div>
      <a class="btn btn-primary btnNext pull-right" id="validateFirst">Next</a>
    </div>
    <div id="personal" class="tab-pane fade">
      <div class="row">
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">First Name *</label>
            <input id="firstname" name="firstname" placeholder="" type="text" class="form-control" value="firstname" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">DOB *</label>
            <input id="dob" name="dob" placeholder="" type="text" class="form-control" value="DOB" readonly="readonly" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputFile">Address  *</label>
            <textarea id="student_address" name="student_address" placeholder="" class="form-control" rows="2"></textarea>
          </div>
        </div>
      </div>
      <a class="btn btn-primary btnPrevious pull-left">Previous</a>
      <a class="btn btn-primary btnNext pull-right">Next</a>
    </div>
    <div id="family" class="tab-pane fade">
      <div class="row">
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Father Name *</label>
            <input id="father_name" name="father_name" placeholder="" type="text" class="form-control" value="father_name" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Father Occupation *</label>
            <input id="father_occupation" name="father_occupation" placeholder="" type="text" class="form-control" value="father_occupation" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Mother Name *</label>
            <input id="mother_name" name="mother_name" placeholder="" type="text" class="form-control" value="mother_name" />
          </div>
        </div>
      </div>
      <a class="btn btn-primary btnPrevious pull-left">Previous</a>
      <button type="submit" class="btn btn-info pull-right">Save</button>
    </div>
  </div>
</form>

其中按钮有$('#validateFirst').click(function () { // Get the Login Name value and trim it var name = $.trim($('#admission_no').val()); // Check if empty of not if (name === '') { alert('Text-field is empty.'); return false; } }); “validateFirst”,

id

这里显示<a class="btn btn-primary btnNext pull-right" id="validateFirst">Next</a> 当未完成录取没有输入但是在单击下一个按钮时移动到下一个标签()个人详细信息。我需要的是当点击下一个按钮时,如果当前alert字段中的字段为空(例如,在第一个导航丸中没有填写入口没有字段)并单击下一个按钮,它应该显示警告并且不应该移动到下一个nav-pill来纠正当前nav-pill中的无效输入字段。我看了看其他问题,但我无法得到明确的解决方案。请帮我解决这个问题。

4 个答案:

答案 0 :(得分:5)

你可以这样做:

$('.pull-right').click(function () {
    var validationMessage = '';

    // Check inputs are filled.
    $.each($(this).closest('.tab-pane').find('input[type="text"]'), function () {
        if ($(this).val() == '') 
            validationMessage += "Please fill " + $(this).closest('.form-group').find('label').html().replace('*', '') + "\n";           
    });

    // Validation is false
    if (validationMessage != '')
        alert(validationMessage);
    else
        $('.nav-pills > .active').next('li').find('a').trigger('click');
});

Online demo (jsFiddle)

答案 1 :(得分:2)

你已经在'.btn-next'上有一个事件处理程序在同一个元素上定义另一个事件处理程序将按照你附加事件处理程序的顺序执行它们。(你可以通过以下方式更改顺序操纵冒泡阶段和捕获阶段,但只有在使用addEventListener时才会起作用。)

解决方案1:

您可以设置一个布尔变量并将验证状态指定给它,并在下一个nav-pill上触发click事件之前检查状态。

在这种方法中,绑定事件处理程序的顺序很重要。

将解决方案附加为

下面的内联代码段

注意:此解决方案不具有可扩展性和可维护性,而且过于天真。

解决方案2:

替代解决方案是您需要确保在单个函数中验证所有内容并读取状态并触发导航丸事件。

https://jsfiddle.net/8b7pq08a/

注意:如果要添加多个验证,例如checkEmpty,则需要对“listOfRequiredFields”进行一些修改。将其转换为具有验证函数作为值的对象将帮助您识别必须在该字段上执行的函数。 [UPDATE]

使用问题中的代码段而不是小提琴。

 var validationStatus = true;
 
//  Bind the event handler to the "submit" JavaScript event
$('#validateFirst').click(function() {

  // Get the Login Name value and trim it
  var name = $.trim($('#admission_no').val());

  // Check if empty or not
  if (name === '') {
    alert('Admission No. field is empty.');
     validationStatus = false;
   }
});

$('.btnNext').click(function() {
if(validationStatus)  $('.nav-pills > .active').next('li').find('a').trigger('click');
});

$('.btnPrevious').click(function() {
  if(validationStatus) $('.nav-pills > .active').prev('li').find('a').trigger('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<ul class="nav nav-pills nav_content">
  <li class="active"><a data-toggle="pill" href="#admission">Admission Details</a></li>
  <li><a data-toggle="pill" href="#personal">Personal Details</a></li>
  <li><a data-toggle="pill" href="#family">Family Details</a></li>
</ul>

<form id="form1" action="<?php echo site_url('student/create') ?>" id="employeeform" name="employeeform" method="post" accept-charset="utf-8" enctype="multipart/form-data">
  <div class="tab-content">
    <div id="admission" class="tab-pane fade in active">
      <div class="row">
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Admission Number *</label>
            <input id="admission_no" name="admission_no" placeholder="" type="text" class="form-control" value="admission_no" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Application Number  *</label>
            <input id="application_no" name="application_no" placeholder="" type="text" class="form-control" value="application_no" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Academic Year  *</label>
            <input id="academic_year" name="academic_year" placeholder="" type="text" class="form-control" value="academic_year" />
          </div>
        </div>
      </div>
      <a class="btn btn-primary btnNext pull-right" id="validateFirst">Next</a>
    </div>
    <div id="personal" class="tab-pane fade">
      <div class="row">
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">First Name *</label>
            <input id="firstname" name="firstname" placeholder="" type="text" class="form-control" value="firstname" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">DOB *</label>
            <input id="dob" name="dob" placeholder="" type="text" class="form-control" value="DOB" readonly="readonly" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputFile">Address  *</label>
            <textarea id="student_address" name="student_address" placeholder="" class="form-control" rows="2"></textarea>
          </div>
        </div>
      </div>
      <a class="btn btn-primary btnPrevious pull-left">Previous</a>
      <a class="btn btn-primary btnNext pull-right">Next</a>
    </div>
    <div id="family" class="tab-pane fade">
      <div class="row">
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Father Name *</label>
            <input id="father_name" name="father_name" placeholder="" type="text" class="form-control" value="father_name" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Father Occupation *</label>
            <input id="father_occupation" name="father_occupation" placeholder="" type="text" class="form-control" value="father_occupation" />
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="exampleInputEmail1">Mother Name *</label>
            <input id="mother_name" name="mother_name" placeholder="" type="text" class="form-control" value="mother_name" />
          </div>
        </div>
      </div>
      <a class="btn btn-primary btnPrevious pull-left">Previous</a>
      <button type="submit" class="btn btn-info pull-right">Save</button>
    </div>
  </div>
</form>

答案 2 :(得分:2)

表单验证不仅仅涉及检查字段是否填写。因此,您应该使用Ajax将相关数据提交到服务器,并使用服务器端表单验证。

在页面顶部添加隐藏的div以显示验证错误:

<div class="alert alert-danger col-xs-12 hidden" id="error"></div>

为所有将触发表单验证的按钮添加共享的“validate”类。我们将有三组不同的验证逻辑。为该字段提供与函数名称匹配的ID(例如“validate_1”,“validate_2”等)。

<a class="btn btn-primary btnNext pull-right validate" id="validate_1">Next</a>
<a class="btn btn-primary btnNext pull-right validate" id="validate_2">Next</a>

更新您的jQuery以包含Ajax POST功能。此函数将数据提交到服务器,您可以在其中使用Codeigniter的本机表单验证:

$('.btnPrevious').click(function() {
  $('.nav-pills > .active').prev('li').find('a').trigger('click');
});


$(document).on('click','.validate',function(e){
    e.preventDefault();
    if($('#error').is(":visible")){
        $('#error').empty().addClass('hidden'); //refresh error message if it was triggered previously
    }
    var form = $(this).closest('form');
    $.ajax({        
        url: this.id,
        type: 'POST',
        data: form.serialize(),
        dataType: 'html',
        success: function(data) {
            var result = $.parseJSON(data);
            if(result["error"]===undefined){
                $('.nav-pills > .active').next('li').find('a').trigger('click');
            }else{
                $('#error').append(result["error"]).removeClass('hidden');
            }
        },
        error: function() { }
    });
});

然后在你的控制器中:

function validate_1(){ //function name matches element id
    $this->load->library('form_validation');    
    $this->form_validation->set_rules('admission_no', 'Admission Number', 'required|integer|greater_than[0]');
    $this->form_validation->set_rules('application_no', 'Application Number', 'required|integer|greater_than[0]');
    $this->form_validation->set_rules('academic_year', 'Academic Year', 'required|integer|greater_than[0]');
    if($this->form_validation->run() == TRUE){
         echo json_encode(array('success' => 1));
    }else{
        echo json_encode(array('error' =>  validation_errors()));
    }
}

function validate_2(){
    $this->load->library('form_validation');    
    $this->form_validation->set_rules('firstname', 'First Name', 'required');
    $this->form_validation->set_rules('dob', 'Date of Birth', 'required');
    $this->form_validation->set_rules('student_address', 'Address', 'required');
    if($this->form_validation->run() == TRUE){
        echo json_encode(array('success' => 1));
    }else{
        echo json_encode(array('error' =>  validation_errors()));
    }
}

这将允许您验证数据是否已提交且数据是否有效。用户仍然可以点击他们自己从一个导航药丸导航到另一个导航药丸,但他们将无法在不填写必要字段的情况下提交表格。

enter image description here

答案 3 :(得分:-2)