2010-09-09 3 views
7

Я разработал форму с несколькими полями для представления шагов при заполнении полной формы. Наборы полей отображаются и скрываются нажатием кнопки (по одному на каждом наборе полей), но я хочу проверить каждый набор полей перед тем, как будет показано следующее.JQuery Подтвердить отдельные поля

Я новичок в JQuery, и у меня проблемы. Я нашел это руководство (http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/), которое позволяет мне проверять различные поля отдельно, но моя проблема заключается в том, как использовать эту проверку для управления отображением и скрытием релевантных полей.

Я думал, что для этого нужно создать функцию из каждого события click для кнопок, но я не могу правильно назвать функцию проверки.

Боюсь, что я сейчас полностью смущен! Помогите!!

ответ

1

Вы можете написать пользовательскую функцию проверки для каждого набора полей и вызвать ее с помощью функции .keyup. Вот пример:

HTML:

<div id="fieldset1"> 
    <input type="text" name="fname" id="fname"> 
</div> 

<div id="fieldset2"> 
    <!--hidden using css--> 
    <input type="text" name="fname" id="fname"> 
</div> 

Javascript:

$('#fieldset1 #fname').keyup(function() { 
    // Runs every time your keystroke is released on this input 
    if($(this).val() == 'Adam') { 
     // Checks to see if the field's value is Adam. If it is, then it shows the next fieldset. Otherwise it hides it. 
     $('#fieldset2').show(); 
    } else { 
     $('#fieldset2').hide(); 
    } 
} 

Это, очевидно, имел в виду как очень простой пример, но он иллюстрирует то, что вам нужно сделать для того, чтобы подтвердить вашей формы и изменить DOM на основе пользовательского ввода.

+0

Спасибо за ваш ответ, я вижу логику в своем ответе, но не хочу, чтобы автоматически показывать следующий Fieldset когда данные вводятся в поле. Могу ли я связать проверку набора полей с кнопкой? например создайте функцию validateFS1(), которая возвращает true, является действительным. –

+0

Да - вы можете использовать кнопку или ссылку - просто вставьте код, который говорит onClick = "validateFS1()", и используйте эту функцию, чтобы показать следующий набор полей, если проверка верна. – Adam

1

Используя плагин jQuery validation, вы можете обойти это, имея несколько форм на одной странице. После этого вы можете позвонить:

$ ('# myFormId') проверки()

о формах интереса одного в то время..

+2

Полезно знать, но я думаю, что есть преимущество иметь все поля в одной форме, возможно, проще отправить – Erich

1

я наткнулся на этом примере просто, прежде чем найти свой вопрос, а прибегая к помощи что-то еще, в надежде, что это поможет кому-то с той же проблемой:

https://djaodjin.com/blog/jquery-multi-step-validation.blog.html

В принципе, по-видимому validation.js только подтверждает видимые поля от по умолчанию.

Вот полный пример код, нажмите через по ссылке, чтобы увидеть объяснение:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"> 
    <title>Multiple step form</title> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> 
    <script type="text/javascript" src="js/jquery-1.9.0.js"></script> 
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script> 
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/additional-methods.js"></script> 
    <style type="text/css"> 
     #personal_information, 
     #company_information{ 
      display:none; 
     } 
    </style> 
</head> 
<body> 
    <div class="container"> 
     <div class="col-lg-5"> 
      <form class="form-horizontal" action="" method="POST" id="myform"> 

       <fieldset id="account_information" class=""> 
        <legend>Account information</legend> 
        <div class="form-group"> 
         <label for="username" class="col-lg-4 control-label">Username</label> 
         <div class="col-lg-8"> 
          <input type="text" class="form-control" id="username" name="username" placeholder="username"> 
         </div> 
        </div> 
        <div class="form-group"> 
         <label for="password" class="col-lg-4 control-label">Password</label> 
         <div class="col-lg-8"> 
          <input type="password" class="form-control" id="password" name="password" placeholder="Password"> 
         </div> 
        </div> 
        <div class="form-group"> 
         <label for="conf_password" class="col-lg-4 control-label">Confirm password</label> 
         <div class="col-lg-8"> 
          <input type="password" class="form-control" id="conf_password" name="conf_password" placeholder="Password"> 
         </div> 
        </div> 
        <p><a class="btn btn-primary next">next</a></p> 
       </fieldset> 

       <fieldset id="company_information" class=""> 
        <legend>Account information</legend> 
        <div class="form-group"> 
         <label for="company" class="col-lg-4 control-label">Company</label> 
         <div class="col-lg-8"> 
          <input type="text" class="form-control" id="company" name="company" placeholder="Company"> 
         </div> 
        </div> 
        <div class="form-group"> 
         <label for="url" class="col-lg-4 control-label">Website url</label> 
         <div class="col-lg-8"> 
          <input type="text" class="form-control" id="url" name="url" placeholder="Website url"> 
         </div> 
        </div> 
        <p><a class="btn btn-primary next">next</a></p> 
       </fieldset> 

       <fieldset id="personal_information" class=""> 
        <legend>Personal information</legend> 
        <div class="form-group"> 
         <label for="name" class="col-lg-4 control-label">Name</label> 
         <div class="col-lg-8"> 
          <input type="text" class="form-control" id="name" name="name" placeholder="Name"> 
         </div> 
        </div> 
        <div class="form-group"> 
         <label for="email" class="col-lg-4 control-label">Email</label> 
         <div class="col-lg-8"> 
          <input type="email" class="form-control" id="email" name="email" placeholder="Email"> 
         </div> 
        </div> 
        <p><a class="btn btn-primary" id="previous" >Previous</a></p> 
        <p><input class="btn btn-success" type="submit" value="submit"></p> 
       </fieldset> 

      </form> 
     </div> 
    </div> 

    <script type="text/javascript"> 
     $(document).ready(function(){ 

      // Custom method to validate username 
      $.validator.addMethod("usernameRegex", function(value, element) { 
       return this.optional(element) || /^[a-zA-Z0-9]*$/i.test(value); 
      }, "Username must contain only letters, numbers"); 

      $(".next").click(function(){ 
       var form = $("#myform"); 
       form.validate({ 
        errorElement: 'span', 
        errorClass: 'help-block', 
        highlight: function(element, errorClass, validClass) { 
         $(element).closest('.form-group').addClass("has-error"); 
        }, 
        unhighlight: function(element, errorClass, validClass) { 
         $(element).closest('.form-group').removeClass("has-error"); 
        }, 
        rules: { 
         username: { 
          required: true, 
          usernameRegex: true, 
          minlength: 6, 
         }, 
         password : { 
          required: true, 
         }, 
         conf_password : { 
          required: true, 
          equalTo: '#password', 
         }, 
         company:{ 
          required: true, 
         }, 
         url:{ 
          required: true, 
         }, 
         name: { 
          required: true, 
          minlength: 3, 
         }, 
         email: { 
          required: true, 
          minlength: 3, 
         }, 

        }, 
        messages: { 
         username: { 
          required: "Username required", 
         }, 
         password : { 
          required: "Password required", 
         }, 
         conf_password : { 
          required: "Password required", 
          equalTo: "Password don't match", 
         }, 
         name: { 
          required: "Name required", 
         }, 
         email: { 
          required: "Email required", 
         }, 
        } 
       }); 
       if (form.valid() === true){ 
        if ($('#account_information').is(":visible")){ 
         current_fs = $('#account_information'); 
         next_fs = $('#company_information'); 
        }else if($('#company_information').is(":visible")){ 
         current_fs = $('#company_information'); 
         next_fs = $('#personal_information'); 
        } 

        next_fs.show(); 
        current_fs.hide(); 
       } 
      }); 

      $('#previous').click(function(){ 
       if($('#company_information').is(":visible")){ 
        current_fs = $('#company_information'); 
        next_fs = $('#account_information'); 
       }else if ($('#personal_information').is(":visible")){ 
        current_fs = $('#personal_information'); 
        next_fs = $('#company_information'); 
       } 
       next_fs.show(); 
       current_fs.hide(); 
      }); 

     }); 
    </script> 
</body> 
</html> 
Смежные вопросы