2016-04-07 75 views
0

我有一段代码在提交前验证表单。这不是我第一次使用此代码,但这是第一次使用boostrap。条件被上下颠倒

这是我第一次注意到条件是从最后一个到第一个评估的:所以如果我试图发布一个空的表单,我会为最后一个字段出错;那么一旦解决了这个错误,它就会移到前一个,然后回到顶端。

我的JS:

$('#submit').click(function(e){ 
    e.preventDefault(); 
    var tipo = <?php echo $tipo; ?>; 
    var error = 0; 
    if ($('#screen_name').val()=='') { 
     $('#message').removeClass().addClass('text-danger').html("<strong><?php echo _("Inserisci il nome della schermata per proseguire."); ?></strong>").fadeTo(900,1); 
     $('#screen_name').focus(); 
     error = error + 1; 
    } 
    if (tipo==1||tipo==2||tipo==3) { 
     if ($('#scroll_text').val()=='') { 
      $('#message').removeClass().addClass('text-danger').html("<strong><?php echo _("Inserisci una testo da fare scorrere per proseguire."); ?></strong>").fadeTo(900,1); 
      $('#scroll_text').focus(); 
      error = error + 1; 
     } 
    } 
    if (tipo==2||tipo==4) { 
     if ($('#templ_img').val()=='') { 
      $('#message').removeClass().addClass('text-danger').html("<strong><?php echo _("Scegli una immagine per proseguire."); ?></strong>").fadeTo(900,1); 
      $('#templ_img').focus(); 
      error = error + 1; 
     } 
    } 
    if (tipo==3||tipo==5) { 
     if ($('#templ_film').val()=='') { 
      $('#message').removeClass().addClass('text-danger').html("<strong><?php echo _("Scegli un video per proseguire."); ?></strong>").fadeTo(900,1); 
      $('#templ_film').focus(); 
      error = error + 1; 
     } 
    } 
    if (error==0) { 
     ajaxSubmit(); 
    } 
}); 

我缺少什么?这段代码有什么问题?假设tipo=2它将评估:

  1. #templ_img
  2. #scroll_text
  3. #screen_name

,但应该是:

  1. #screen_name
  2. #scroll_text
  3. #templ_img

,既在形式和JS代码序列。

+0

当然你不想要'elseif'?如果只有“如果”,你总是有机会重写先前做过的事情。 – Yoshi

+0

@Yoshi你说得对。他们每个人都这样覆盖前一个,所以我只看到最后一个。谢谢,这解决了我的问题 –

回答

0

根据@Yoshi的建议,我通过包装每个if语句来检查前一个是否已经出错,从而解决了这个问题。

if (error==0) { 
    if (tipo==1||tipo==2||tipo==3) { 
     if ($('#scroll_text').val()=='') { 
      $('#message').removeClass().addClass('text-danger').html("<strong><?php echo _("Inserisci una testo da fare scorrere per proseguire."); ?></strong>").fadeTo(900,1); 
      $('#scroll_text').focus(); 
      error = error + 1; 
     } 
    } 
} 

例如。 我的代码覆盖了下面的错误。 Else If是不适用的,因为其他是为内部的,但我首先检查tipo值。