【问题标题】:How to Prevent a panel from going to next panel when input fields are empty输入字段为空时如何防止面板转到下一个面板
【发布时间】:2026-02-23 23:10:01
【问题描述】:

我有一个基于包含表单的面板的问题。如何防止在包含空表单字段的起始面板上单击“下一步”?如果表格是在第一个面板中填写的,那么“下一步”按钮将允许用户转到下一个面板。在我提供的代码中,当输入字段为空时,用户可以从面板 1 转到面板 2。但是,在面板 2 中,用户在填写表格之前无法继续(这就是显示验证消息的原因)。我一直在努力解决这个问题,进行了大量研究,但未能找到解决方案。任何人都可以根据我正在使用的当前代码为我提供帮助。非常感谢您的参与。 (也有一些原因,在空输入上单击提交时,选项卡会关注最后一个输入而不是第一个)

我尝试了什么 btnNext 类允许我转到下一个面板。因此,当输入字段为空时,将删除 btnNext 类。填写完字段后,将添加类,允许用户移动到下一张幻灯片。这适用于面板 2。但是当启动面板 1 时,btnNext 存在,允许我在字段为空时转到第二张幻灯片。

改进如果我在这个问题上得到否定,请告诉我原因,以便我整体改进我的问题。谢谢,

// JavaScript Document
$(document).ready(function() {
  /*goes to next and prev panels when selecting next and previous*/
  $('.btnPrev').css('display', 'none'); //hides the prev button when starting the panel
  $(document).ready(function() {
    var $fieldsets =
      $('#panels .sets')
      .first()
      .addClass('active')
      .end()
      .not(':first')
      .hide()
      .end();

    var $panelControlButtons =
      $('#panelcontrol button')
      .filter('.btnPrev')
      .prop('disabled', true)
      .end();

    $('#panelcontrol')
      .on('click', 'button', function(e) {
        e.preventDefault();

        switch (true) {
          case $(this).hasClass('btnNext'):
            var $newFieldset =
              $fieldsets
              .filter('.active')
              .hide()
              .removeClass('active')
              .next()
              .addClass('active')
              .show();


            /*----------------------------VALIDATING-------------------------*/
            $('.btnNext').click(function(e) {
              var focusSet = false;
              // JavaScript Document
              function validateNumber(number) {
                /*  var numberPattern = /[^A-Za-z]/;*/
                var regex = /^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/;
                var numStr = "123.20";
                return regex.test(number);
                return numStr.test(number);
              }


              //1 - OTHER AMOUNT
              if ($('#first_panel_monthly').hasClass('active')) { //ONLY IF ON THIRD PANEL
                if (!$('#input_otherAmount').val()) {
                  if ($('#input_otherAmount').parent().next('.Inval').length == 0) {
                    $("#input_otherAmount").parent().after("<div class='Inval Input_Msg Gft_Amount_Msg'>Please select or enter a gift amount</div>");
                  }
                  $('#input_otherAmount').focus();
                  focusSet = true;

                } else {
                  $("#input_otherAmount").parent().next(".Inval").remove();
                }



                if (!validateNumber($('#input_otherAmount').val())) {
                  if ($('#input_otherAmount').parent().next('.Inval').length == 0) {
                    $("#input_otherAmount").parent().after("<div class='Inval Input_Msg Gft_Amount_Msg'>Please select or enter a gift amount</div>");
                  }
                  $('#input_otherAmount').focus();
                  focusSet = true;

                }
              } else {
                //ok
                $("#input_otherAmount").parent().next(".Inval").remove();
              }


              // 2 - FIRST NAME
              if ($('#second_panel_monthly').hasClass('active')) { //ONLY IF ON SECOND
                if (!$('#firstName').val()) {
                  //if not valid
                  if ($('#firstName').parent().next('.Inval').length == 0) {
                    $("#firstName").parent().after("<div class='Inval Input_Msg'>Please enter first name</div>");
                  }
                  $('#firstName').focus();
                  focusSet = true;

                } else {
                  //ok
                  $("#firstName").parent().next(".Inval").remove();
                }

              } else {
                $("#firstName").parent().next(".Inval").remove();
              }
              //hides and display next button class based on value
              if (focusSet) {
                $("#continue_btn").removeClass("btnNext"); //remove class for continue button. Disabling continue
              } else {
                $("#continue_btn").addClass('btnNext'); //adds class for the continue button. Enabling continue
              }


              // 3 -  LAST NAME
              if ($('#second_panel_monthly').hasClass('active')) {
                if (!$('#lastName').val()) {

                  if ($('#lastName').parent().next('.Inval').length == 0) {
                    $("#lastName").parent().after("<div class='Inval Input_Msg'>Please enter last name</div>");
                  }
                  $('#lastName').focus();
                  focusSet = true;

                } else {
                  //ok
                  $("#lastName").parent().next(".Inval").remove();
                }

                // validate email - email format

              } else {
                //ok
                $("#lastName").parent().next(".Inval").remove();
              }
              //hides and display next button class based on value
              if (focusSet) {
                $("#continue_btn").removeClass("btnNext"); //remove class for continue button. Disabling continue
              } else {
                $("#continue_btn").addClass('btnNext'); //adds class for the continue button. Enabling continue
              }


            });
            /*------------------------------END OF VALIDATING----------------------------*/

            //enable Prev button
            $panelControlButtons
              .filter('.btnPrev')
              .prop('disabled', false);
            $('.btnPrev').css('display', 'block');

            //disabled Next button
            if ($newFieldset.is(':last-child')) {
              $panelControlButtons
                .filter('.btnNext')
              /*.prop('disabled', true);	*/
              $(':last-child').find(".btnNext").text("Place Payment"); //once last child element, btn will change text 
            }


            break; // btnNext

          case $(this).hasClass('btnPrev'):
            var $newFieldset =
              $fieldsets
              .filter('.active') //selects the current fieldset
              .hide() //hide it	
              .removeClass('active') //remove active flag
              .prev() //move to the previous fieldset
              .addClass('active') //flag as active
              .show(); //and show it



            // enable Next button
            $panelControlButtons
              .filter('.btnNext')
              .prop('disabled', false);
            $(':last-child').find(".btnNext").text("Continue"); //"Next" text will be added will appear when prev is selected

            // disable Prev button			
            if ($newFieldset.is(':first-child')) {
              $panelControlButtons
                .filter('.btnPrev').css('display', 'none') //Hides the prev button when going back to the first set of the panel
                .prop('disabled', true);
            }
            break; // btn Prev

        }

      }); // panelcontrol button handler

  });

}); //end of document ready
<!doctype html>
<html lang="en">

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
  <!-- Panel 2 (monthly) starts here -->
  <div id="panels">
    <!--Sets-->
    <div class="sets" id="first_panel_monthly">
      <table>
        <tr>
          <td>
            <form>
              <fieldset>
                <div class="form-group">
                  <label for="total" class="control-label">Other Amount</label>
                  <input type="text" name="total" id="input_otherAmount" class="input-control" />
                </div>
              </fieldset>
            </form>
          </td>
        </tr>
      </table>
    </div>
    <!--End of sets-->
    <!--Sets-->
    <div class="sets" id="second_panel_monthly">
      <h3>Contact Information</h3>
      <div>
        <label for="firstName">First Name</label>
        <input type="firstName" class="form-control" id="firstName" />
      </div>
      <div>
        <label for="lastName">Last Name</label>
        <input type="lastName" class="form-control" id="lastName" />
      </div>
      <div>
        <label class="label-effect" for="phonePanelTwo">Phone Number</label>
        <input type="phonePanelTwo" class="form-control" id="phonePanelTwo" />
      </div>
    </div>
    <!--End of sets-->
  </div>
  <!----End of panel---->
  <div class="row">
    <div id="panelcontrol">
      <button class="btnPrev btn_panel_style">Previous</button>
      <div class="btn_grid_wrapper">
        <button id="continue_btn" class="btnNext btn_panel_style">Continue</button>
      </div>
    </div>
  </div>
  <!--cust: -->
  <script src="js/form-validate-one.js"></script>
</body>

</html>

【问题讨论】:

    标签: javascript jquery forms validation panels


    【解决方案1】:

    我删除了您的代码中的嵌套 document.ready 函数。我使用了您的代码的零碎部分,但不是全部。希望这会有所帮助..

        <!doctype html>
        <html lang="en">
    
        <head>
          <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        </head>
    
        <body>
          <!-- Panel 2 (monthly) starts here -->
          <form id="myForm">
          <fieldset>
          <div id="panels">
            <!--Sets-->
            <div class="sets" id="first_panel_monthly">
              <table>
                <tr>
                  <td>
    
                        <div class="form-group">
                          <label for="total" class="control-label">Other Amount</label>
                          <input type="text" name="total" id="input_otherAmount" class="input-control" />
                        </div>
    
                  </td>
                </tr>
              </table>
            </div>
            <!--End of sets-->
            <!--Sets-->
            <div class="sets" id="second_panel_monthly">
              <h3>Contact Information</h3>
              <div>
                <label for="firstName">First Name</label>
                <input name="firstName" type="text" class="form-control" id="firstName" />
              </div>
              <div>
                <label for="lastName">Last Name</label>
                <input name="lastName" type="text" class="form-control" id="lastName" />
              </div>
              <div>
                <label class="label-effect" for="phonePanelTwo">Phone Number</label>
                <input name="phonePanelTwo" type="tel" class="form-control" id="phonePanelTwo" />
              </div>
            </div>
            <!--End of sets-->
            <!--Sets-->
            <div class="sets" id="third_panel_monthly">
              <h3>Contact Information</h3>
              <div>
                <label for="firstName">First Name</label>
                <input name="firstName2" type="text" class="form-control" id="firstName2" />
              </div>
              <div>
                <label for="lastName">Last Name</label>
                <input name="lastName2" type="text" class="form-control" id="lastName2" />
              </div>
              <div>
                <label class="label-effect" for="phonePanelTwo">Phone Number</label>
                <input name="phonePanelThree" type="tel" class="form-control" id="phonePanelThree" />
              </div>
            </div>
            <!--End of sets-->            
          </div>
          </fieldset>
          </form>
          <!----End of panel---->
          <div class="row">
            <div id="panelcontrol">
              <button class="btnPrev btn_panel_style">Previous</button>
              <div class="btn_grid_wrapper">
              <button id="continue_btn" class="btnNext btn_panel_style">Continue</button>
              </div>
            </div>
          </div>
          <!--cust: -->
        <!--  <script src="js/form-validate-one.js"></script>-->
    
    
        <script>
            // JavaScript Document
            $(document).ready(function() {
              /*goes to next and prev panels when selecting next and previous*/
              $('.btnPrev').css('display', 'none'); //hides the prev button when starting the panel
    
                var $fieldsets =
                  $('#panels .sets')
                  .first()
                  .addClass('active')
                  .end()
                  .not(':first')
                  .hide()
                  .end();
    
                var $panelControlButtons =
                  $('#panelcontrol button')
                  .filter('.btnPrev')
                  .prop('disabled', true)
                  .end();
    
                var focusSet = false;
    
                function validateNumber(number) {
                  /*  var numberPattern = /[^A-Za-z]/;*/
                  var regex = /^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/;
                  var numStr = "123.20";
                  return regex.test(number);
                  return numStr.test(number);
                }
    
                function showNextDiv() {
                      var nextDiv = $(".sets:visible").next(".sets");
                      var first = 0;
                      if (nextDiv.length == 0) { 
                        // nextDiv = $(".sets:first"); // wrap around to beginning
                        // submit the form
                        $("#myForm").submit();
                        first = 1;
                      }
                      else {
                          first = 0;
                      }
                      $(".sets").hide();
                      $(".sets").removeClass('active');
                      nextDiv.show(); 
                      nextDiv.addClass('active');
    
                      if(first != 1) {
                          $(".btnPrev").show();
                          $(".btnPrev").prop('disabled', false);
                      }
                      else {
                          $(".btnPrev").hide();
                          $(".btnPrev").prop('disabled', true);                        
                      }
                }
    
                $(".btnPrev").click(function() {
                    console.log("previous");
                  var prevDiv = $(".sets:visible").prev(".sets");
    
                  console.log(prevDiv);
                  if (prevDiv.length == 0) { // wrap around to end
                      prevDiv = $(".sets:last");
                  }
                  $(".sets").hide();
                  $(".sets").removeClass('active');
                  prevDiv.show();
                  prevDiv.addClass('active');
    
                  if (prevDiv.is('.sets:first')) {
                      console.log("first");
                          $(".btnPrev").hide();
                          $(".btnPrev").prop('disabled', true);                      
                  }
                  else {
                          $(".btnPrev").show();
                          $(".btnPrev").prop('disabled', false);                    
                  }
    
                });
    
                $('#panelcontrol')
                  .on('click', '.btnNext', function(e) {
                    //e.preventDefault();
                          //1 - OTHER AMOUNT
                          if ($('#first_panel_monthly').hasClass('active')) { //ONLY IF ON FIRST PANEL
    
                            if (!$('#input_otherAmount').val()) {
                              if ($('#input_otherAmount').parent().next('.Inval').length == 0) {
                                $("#input_otherAmount").parent().after("<div class='Inval Input_Msg Gft_Amount_Msg'>Please select or enter a gift amount</div>");
                              }
                              $('#input_otherAmount').focus();
                              focusSet = true;
    
    
                            }
                            else 
                              if (!validateNumber($('#input_otherAmount').val())) {
                              if ($('#input_otherAmount').parent().next('.Inval').length == 0) {
                                $("#input_otherAmount").parent().after("<div class='Inval Input_Msg Gft_Amount_Msg'>Please select or enter a gift amount</div>");
                              }
                              $('#input_otherAmount').focus();
                              focusSet = true;
                            }
                            else {
                              $("#input_otherAmount").parent().next(".Inval").remove();
                              //$("#continue_btn").prop('disabled', true);
                              focusSet = false;
                              console.log("first panel ok");
    
                              showNextDiv();                                    
                            }
    
                          }
                          else if($('#second_panel_monthly').hasClass('active')) { //ONLY IF ON SECOND PANEL
    
                            if (!$('#firstName').val()) {
                              if ($('#firstName').parent().next('.Inval').length == 0) {
                                $("#firstName").parent().after("<div class='Inval Input_Msg Gft_Amount_Msg'>Please enter first name</div>");
                              }
                              $('#firstName').focus();
                              focusSet = true;
                            } 
                            else if (!$('#lastName').val()) {
                              $("#firstName").parent().next(".Inval").remove();
                              if ($('#lastName').parent().next('.Inval').length == 0) {
                                $("#lastName").parent().after("<div class='Inval Input_Msg Gft_Amount_Msg'>Please enter last name</div>");
                              }
                              $('#lastName').focus();
                              focusSet = true;
                            }
                            else {
                                $("#firstName").parent().next(".Inval").remove();
                                $("#lastName").parent().next(".Inval").remove();
                               console.log("second panel ok");  
                               showNextDiv();
                            }                 
    
                        }
                        else { // IF THIRD Panel
    
    
                            if (!$('#firstName2').val()) {
                              if ($('#firstName2').parent().next('.Inval').length == 0) {
                                $("#firstName2").parent().after("<div class='Inval Input_Msg Gft_Amount_Msg'>Please enter first name</div>");
                              }
                              $('#firstName2').focus();
                              focusSet = true;
                            } 
                            else if (!$('#lastName2').val()) {
                              $("#firstName2").parent().next(".Inval").remove();
                              if ($('#lastName2').parent().next('.Inval').length == 0) {
                                $("#lastName2").parent().after("<div class='Inval Input_Msg Gft_Amount_Msg'>Please enter last name</div>");
                              }
                              $('#lastName2').focus();
                              focusSet = true;
                            }
                            else if(!$('#phonePanelThree').val()) {
                              $("#firstName2").parent().next(".Inval").remove();
                              $("#lastName2").parent().next(".Inval").remove();
                              if ($('#phonePanelThree').parent().next('.Inval').length == 0) {
                                $("#phonePanelThree").parent().after("<div class='Inval Input_Msg Gft_Amount_Msg'>Please enter phone number</div>");
                              }
                              $('#phonePanelThree').focus();
                              focusSet = true;                                
                            }
                            else {
                                $("#firstName2").parent().next(".Inval").remove();
                                $("#lastName2").parent().next(".Inval").remove();
                               console.log("third panel ok");  
                               showNextDiv();
                            }                            
    
    
                        }
    
                  }); // panelcontrol button handler
    
            }); //end of document ready
        </script>
    
        </body>
    
    </html>
    

    【讨论】:

    • 谢谢,但是如果我添加另一个面板呢?我添加了另一个面板,但第三个面板上的表单没有显示。我还注意到,验证消息一次只显示在面板 2 上的一个字段上,而不是在所有空字段上显示所有验证消息。 (面板 2)。这段代码对我来说是否灵活,可以将验证消息添加到包含活动类的所有表单?非常感谢您的宝贵时间
    • 添加了第三个面板 - 复制粘贴了第二个面板。由于在您的代码中没有对电话号码进行验证,因此没有包含相同的内容。在第三个面板中添加了相同的验证。在所有面板结束时,表单被提交。