2015-03-10 4 views
0

Итак, я взял этот код из этого website. Я не хочу иметь все поля поля обязательные для заполнения. Например, допустим, полное среднее имя. Я хочу, чтобы это поле было необязательным (следовательно, не влияя на функцию проверки, какие поля имеют ошибку). Как мне это сделать?Как я могу сделать поле НЕ обязательным в этом коде?

$(function() { 
    /* 
    number of fieldsets 
    */ 
    var fieldsetCount = $('#formElem').children().length; 

    /* 
    current position of fieldset/navigation link 
    */ 
    var current  = 1; 

    /* 
    sum and save the widths of each one of the fieldsets 
    set the final sum as the total width of the steps element 
    */ 
    var stepsWidth = 0; 
    var widths  = new Array(); 
    $('#steps .step').each(function(i){ 
     var $step  = $(this); 
     widths[i]  = stepsWidth; 
     stepsWidth  += $step.width(); 
    }); 
    $('#steps').width(stepsWidth); 

    /* 
    to avoid problems in IE, focus the first input of the form 
    */ 
    $('#formElem').children(':first').find(':input:first').focus(); 

    /* 
    show the navigation bar 
    */ 
    $('#navigation').show(); 

    /* 
    when clicking on a navigation link 
    the form slides to the corresponding fieldset 
    */ 
    $('#navigation a').bind('click',function(e){ 
     var $this = $(this); 
     var prev = current; 
     $this.closest('ul').find('li').removeClass('selected'); 
     $this.parent().addClass('selected'); 
     /* 
     we store the position of the link 
     in the current variable 
     */ 
     current = $this.parent().index() + 1; 
     /* 
     animate/slide to the next or to the corresponding 
     fieldset. The order of the links in the navigation 
     is the order of the fieldsets. 
     Also, after sliding, we trigger the focus on the first 
     input element of the new fieldset 
     If we clicked on the last link (confirmation), then we validate 
     all the fieldsets, otherwise we validate the previous one 
     before the form slided 
     */ 
     $('#steps').stop().animate({ 
      marginLeft: '-' + widths[current-1] + 'px' 
     },500,function(){ 
      if(current == fieldsetCount) 
       validateSteps(); 
      else 
       validateStep(prev); 
      $('#formElem').children(':nth-child('+ parseInt(current) +')').find(':input:first').focus();  
     }); 
     e.preventDefault(); 
    }); 

    /* 
    clicking on the tab (on the last input of each fieldset), makes the form 
    slide to the next step 
    */ 
    $('#formElem > fieldset').each(function(){ 
     var $fieldset = $(this); 
     $fieldset.children(':last').find(':input').keydown(function(e){ 
      if (e.which == 9){ 
       $('#navigation li:nth-child(' + (parseInt(current)+1) + ') a').click(); 
       /* force the blur for validation */ 
       $(this).blur(); 
       e.preventDefault(); 
      } 
     }); 
    }); 

    /* 
    validates errors on all the fieldsets 
    records if the Form has errors in $('#formElem').data() 
    */ 
    function validateSteps(){ 
     var FormErrors = false; 
     for(var i = 1; i < fieldsetCount; ++i){ 
      var error = validateStep(i); 
      if(error == -1) 
       FormErrors = true; 
     } 
     $('#formElem').data('errors',FormErrors); 
    } 

    /* 
    validates one fieldset 
    and returns -1 if errors found, or 1 if not 
    */ 
    function validateSteps(){ 
     var FormErrors = false; 
     for(var i = 1; i < fieldsetCount; ++i){ 
      var error = validateStep(i); 
      if(error == -1) 
       FormErrors = true; 
     } 
     $('#formElem').data('errors',FormErrors); 
    } 

    /* 
    validates one fieldset 
    and returns -1 if errors found, or 1 if not 
    */ 

    function validateStep(step){ 
     if(step == fieldsetCount) return; 

     var error = 1; 
     var hasError = false; 
     $('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){ 
      var $this  = $(this); 
      var valueLength = jQuery.trim($this.val()).length; 

      if(valueLength == '') 
      { 
       hasError = true; 

       $this.css('background-color','red');   
      } 
      else 
      { 
       $this.css('background-color','yellow'); 
      } 

     } 


     ); 


     var $link = $('#navigation li:nth-child(' + parseInt(step) + ') a'); 
     $link.parent().find('.error,.checked').remove(); 

     var valclass = 'checked'; 

     if(hasError) 
     { 

      error = -1; 
      valclass = 'error'; 
     } 
     $('<span class="'+valclass+'"></span>').insertAfter($link); 

     return error; 
    } 


    /* 
    if there are errors don't allow the user to submit 
    */ 
    $('#registerButton').bind('click',function(){ 
     if($('#formElem').data('errors')){ 
      alert('Please correct the errors in the Form'); 
      return false; 
     } 
    }); 
}); 
+0

Если вы не указали требуемое значение элемента, то оно не требуется. – PHPglue

ответ

2

внутри validateStep функции на линии, где вы выполняете находку просто добавить этот тег после :input, как показано ниже:

$('#formElem').children(':nth-child('+ parseInt(step)+')').find(':input[required]:not(button)') 

Вы просто должны использовать атрибут required HTML внутри вашей веб-страницы, и когда вы будете запустите функцию validateStep, она будет игнорировать все поля без атрибута required.

Посмотрите на mdn doc для получения дополнительной информации. https://developer.mozilla.org/en-US/docs/Web/CSS/:required

+0

Как именно? поэтому я заменяю от $ ('# formElem'). children (': nth-child (' + parseInt (step) + ')'). find (': input: not (button)'). each (function() – dawn

+0

yeap попробуйте добавить '[обязательно]' внутри вашего параметра поиска, но обязательно добавьте этот обязательный атрибут в свои поля внутри вашей формы. – babar78

+1

Это работает, см. Это [ jsFiddle] (http://jsfiddle.net/awolf2904/Lbv8rgzw/) для демонстрации. Я также добавил атрибут «требовать все», если вы добавили «обязательный» в поле, все входные данные требуются. Скользить личные данные Я добавил обязательные только для полного имени и страны. – AWolf