2014-09-11 57 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');    
         } 
    }); 
});