2015-02-09 50 views
1

我有一個4輸入(甚至可以更多)的表單,用戶可以放置一個數字或什麼都不是。唯一的規則是,如果您在輸入中輸入數字,則如果在另一個輸入中輸入相同的數字(無重複),則無法提交數字。您可以根據需要提交儘可能多的空輸入。基於長度比較兩個數組:跳過空值

爲了驗證輸入,我只用唯一值比較了具有相同數組的所有輸入數組的長度。如果他們有相同的長度沒關係。 我需要改進我的代碼,因爲現在只有當用戶輸入所有輸入字段時纔有效。如果某些輸入爲空,則它們在數組中被視爲具有唯一值,因爲它們都具有「」作爲值。所以,如果用戶只輸入一個數字,我會得到數組長度爲4,數組唯一爲2,但它應該是1和1(跳過空白項)。

我在考慮在arr上使用splice(),但是這是做這種驗證的最好方法嗎? **編輯:我應用拼接,但如果數組是('1','','')我的代碼給我('1',''),而不僅僅是(1),因爲我期望... **這是因爲拼接刪除項目並更改數組長度,以便for循環指向錯誤的索引。 有什麼想法? HTML:

<div class="sez-form"> 
    <fieldset> 
     <legend>Messaggi inclusi</legend> 
     <div class="percheckbox"> 
      <input class="checkseq" type="checkbox" value="1" name="messaggio[0]"> 
      Prova di messaggio che scorre<br> 
      <label>Ordine: </label> 
      <input class="seq" type="text" name="ordine[0]" maxlength="2" size="2"> 
     </div> 

     <div class="percheckbox"> 
      <input class="checkseq" type="checkbox" value="3" name="messaggio[1]"> 
      Titoli di film<br> 
      <label>Ordine: </label> 
      <input class="seq" type="text" name="ordine[1]" maxlength="2" size="2"> 
     </div> 

     <div class="percheckbox"> 
      <input class="checkseq" type="checkbox" value="6" name="messaggio[2]"> 
      Prova a testo fisso<br> 
      <label>Ordine: </label> 
      <input class="seq" type="text" name="ordine[2]" maxlength="2" size="2"> 
     </div> 
     <br style="clear: both;"> 
    </fieldset> 
</div> 

JAVASCRIPT:

function uniqueArray(arr) { 
    return $.grep(arr,function(v,k) { 
     return $.inArray(v,arr) === k; 
    }); 
} 

$(document).ready(function() { 
    $('#invia').click(function(e) { 
     e.preventDefault(); 
     var arr = $(".seq").map(function(){ return $(this).val(); }).toArray(); 
     var empty = $(".seq").filter(function() { 
      return this.value == ""; 
     }) 
    for (index = 0; index < arr.length; ++index) { 
     if (arr[index]=='') { 
      new_arr = arr.splice([index],1); 
     } 
     console.log(arr); 
    } 

     if(empty.length == $('.seq').length) { 
      alert('Non hai scelto alcun messaggio per il workflow. Correggi per procedere.'); 
     } 
     else if(uniqueArray(arr).length != $('.seq').length) { 
      console.log(uniqueArray(arr)); 
      alert('Ci sono voci duplicate nella sequenza. Correggi per procedere.'); 
     } 
     else if($('#dt_from').val()=='__/__/____ __:__') { 
      alert('Scegli data e ora di inizio validit\u00E0 per il workflow'); 
     } 
     else if($('#dt_to').val()=='__/__/____ __:__') { 
      alert('Scegli data e ora di fine validit\u00E0 per il workflow'); 
     } 
     else { 
      ajaxSubmit(); 
     } 
    }); 
}); 

回答

0

使用散列爲你迭代跟蹤值。此示例僅返回truefalse,但您也可以掃描整個數組並返回重複的值。

function uniquifyArray(ary) { 
    var seen = {}; 
    var isUnique = true; 
    /* iterate backwards since the array length will change as elements are removed */ 
    for (var i=ary.length; i--;) { 
     /* remove blank/undefined */ 
     if (typeof ary[i] === 'undefined' || ary[i] === '') {     
      ary.splice(i,1); 
     } else { 
      /* check if this value has already been seen */ 
      if (ary[i] in seen) { 
       isUnique = false; 
       ary.splice(i,1); 
      } else { 
       seen[ary[i]]=true; 
      } 
     } 
    } 
    ary = ary.sort(); 
    return isUnique; 
} 

var test = [ '1','2','','','3','4','1' ]; 
uniquifyArray(test); // returns false, test = [ '1','2','3','4' ] 

test = [ '1','2','','' ] 
uniquifyArray(test); //true, test = ['1','2'] 
+0

If thisUniqueArray(['1','2','','','3','4','1']);是用戶輸入它應該給我isUniqueArray(['1','2','','3','4']);這是錯誤的',因爲輸入是7項,輸出只有5(存在重複)。我想排序輸入,在isUniqueArray(['1','2','3','4','1'))中更改它。即5項 – 2015-02-09 15:49:38

+0

這是一個驗證函數 - 根本不修改這些值。看來你想要一個功能,將排序,剝離空白_and_失敗,如果有重複? – 2015-02-09 15:56:03

+0

是的,現在我檢查arr和arrUnique的長度......空白項目應該被跳過,因爲我可以發佈一個數組,甚至有一個值,兩個空,但我不能將這個選項添加到我的代碼 – 2015-02-09 15:58:24

1

也許我不明白你正在嘗試做的,但你爲什麼不能喜歡的東西做得很乾脆:

$('#invia').click(function(e) { 
    e.preventDefault(); 
    var unique = [], nonunique = []; 
    $(".seq").each(function(index){ 
     var val = $(this).val(); 
     if (val !== "") { 
      if ($.inArray(val, unique) !== -1) { 
       nonunique.push(val); 
      } else { 
       unique.push(val); 
      } 
     } 
    }); 
    // If unique and nonunique are empty, all inputs were blank 
    // else if nonunique is empty, inputs are valid and in unique 
}); 
+0

將嘗試。或多或少,它符合我的要求。或者甚至在我的兩個驗證中。會嘗試讓你知道! – 2015-02-09 16:25:03

+0

也不錯。我選擇了另一個答案只是因爲它接近我的實際代碼。非常感謝雙方! – 2015-02-09 16:27:23

+0

我注意到我輸入得太快,忘記提取值。我修正了這個例子。 – bobdye 2015-02-09 16:27:42

1

這裏是來處理它另一種可能的方式。 Here is the working JSFiddle.這裏是代碼:

$(function() { 
    $("#submit").click(function() { 
     //build a profile of the inputs 
     var inputs = []; 
     var values = []; 
     var dups = false; //track duplicates on pass 1 

     $(".seq").each(function(i, el) { 
      var empty = (el.value == ""); //check if empty 
      var exists = (!empty && $.grep(inputs, function(item, index) { 
       return (item.Value === el.value); 
      }).length > 0); //check if exists 
      dups = (dups || exists); //track dups 

      //add the new input item 
      var obj = { 
       Element: el, 
       Value: el.value, 
       Empty: empty, 
       Exists: exists 
      }; 
      inputs.push(obj); 

      //conditionally add the sorting value 
      if (!empty && !exists) 
       values.push(el.value); 
     }); 

     //Validate the inputs. If there are duplicates, don't submit 
     $(".seq").css("background-color", "white"); //clear errors 
     if (dups) { 
      $(inputs).each(function(i, el) { 
       if (el.Exists) 
        el.Element.style.backgroundColor = "red"; 
      }); 
     } else { 
      values = values.sort(); 
      alert(values); 
     } 
    }); 
}); 

使用這種方法,在結束時,你有一個數組 - inputs - 所有與他們的狀態元素的,這樣就可以提供錯誤處理的具體領域。在我的例子中,錯誤字段變爲紅色。

alert處,您有一個有序值的排序數組。