2014-09-11 60 views
2

我试图找到我的问题在其他帖子的解决方案,但我找不到类似的东西。比较数组值和索引值在每个()jquery

我有这个网站结构:

<p>title abc</p> 
<input name="input_a" ... > 
<p>title abc</p> 
<input name="input_b" ... > 
<p>title abc</p> 
<input name="input_c" ... > 
... 

提交我在阿贾克斯检查所有字段填写正确的形式,如果一切顺利,将返回“成功”,否则它会返回一个数组包含未验证字段的索引。

例如,如果我填表的只有“input_b”,那么我会得到rs_prod = Array(0, '', 2, 3, ...)

我想现在要做的仅仅是在红色与这些值<p>title abc</p>颜色,添加类。

所以,我的每个值rs_prod[index]比较index

$.ajax({ 
... 
success: function(rs_prod) { 

    if (rs_prod == 'success') { 
     // success case 
    } else { 
     $(rs_prod).each(function(index) { 
      if (index == rs_prod[index]) { 
       $("#add-form p:eq("+index+")").addClass("redText"); 
      } else { 
       console.log(index); // never returns 0 
       $("#add-form p:eq("+index+")").removeClass("redText"); 
      } 
     }); 
    } 
} 

这是工作,其实所有错误的领域我越来越:

<p class= "redText">title abc</p> 

在这一点上,当我我要填写之前忘了的字段,然后再次提交,我应该将课程'redText'删除:所以它会发生......除了第一个<p>title abc</p>保留课程'redText'和我不明白为什么。

我注意到的唯一的事情就是console.log(index),在上面的代码中,总是返回除了当值应为0似乎莫名其妙指数宽松的值为0

编辑/解决方案的索引值:

我认为这个问题主要是由于0由于某种原因不被认为是价值,而是错误的。

这在AJAX使用的阵列来存储字段进行检查:

$fields_req = array(
    0 => 'input1', 
    1 => 'input2', 
    2 => 'input3', 
    3 => 'input4', 
    ...) 

我在

$fields_req = array(
    1 => 'input1', 
    2 => 'input2', 
    3 => 'input3', 
    4 => 'input4', 
    ...) 

然后改变由@Thomas所建议我取代

if (index == rs_prod[index]) { 

if (rs_prod[index]) { 

,现在,它的工作原理

最后编辑时间:这是我的最终解决方案:

if (rs_prod == 'success') { 
    // success case 
} else { 
    $("#add-form p").removeClass("redText"); 

    $(rs_prod).each(function(index) { 
    if (rs_prod[index]) { 
     $("#add-form p:eq("+index+")").addClass("redText"); 
    } 
}); 
+1

而不是'如果(指数== rs_prod [指数]){...}','尝试如果(rs_prod [指数]){...}' – 1252748 2014-09-11 01:37:00

+1

为什么不你发回无效条目的字段名称吗?少得多的猜测工作 – charlietfl 2014-09-11 01:40:11

+0

当执行'console.log(rs_prod)'时,'rs_prod'看起来像什么? (对于不成功的案例。) – flowstoneknight 2014-09-11 01:56:59

回答

0

请检查index价值,看它是否与1 or 0开始。

如果它以1开头,则增加index+ 1并将其用于您的循环。

0

这是可能对您有用的FIDDLE

它不包含AJAX调用,但代码的概念可以很容易地转移到ajax成功或.done函数。

只需点击一下,即可读取所有变量并填充数组。

根据输入值的长度(或可能用于验证的其他标准),输入标签的颜色会更改为红色或蓝色。

我不确定你在用ajax做什么,但是我相信你可以回忆一下ajax,如果你通过第二次点击更新一个或多个变量。

也许通过提供更多信息,我们可能能够帮助您更多。

JS

var firstarray = []; 

$('#clickme').on('click', function(){ 
       $('input').each(function(index){ 
        firstarray[index] = $('input:eq(' + index + ')').val(); 
        console.log(firstarray[index]); 
               }); 
        console.log(firstarray); 
       $('p').each(function(index){ 
        if(firstarray[index].length < 1) 
        { 
         $('p:eq(' + index + ')').css('color', 'red'); 
         } 
         else 
        { 
         $('p:eq(' + index + ')').css('color', 'blue');    
         } 
    }); 
});