2013-05-03 63 views
0

我有一個非常簡單的問題,但我不能解決它。JQuery比較任何匹配數組

表單提交我想比較兩個隱藏輸入類型的值,如果發現任何匹配,則向用戶返回警報並阻止提交。幾乎隱藏的輸入類型值將是1-3,可能是1,12,123,13等。所以如果1和123,發出警報。

所以我嘗試過這樣的事情,但我顯然對我在做什麼感到困惑。

var new_products = $('#new_products'); 
var array_new_products = jQuery.makeArray(new_products); 
var existing_products = $('#existing_products'); 
var array_existing_products = jQuery.makeArray(existing_products); 

$("#my_form").submit(function(e) { 

if (jQuery.inArray(existing_products, new_products) >= 0) { 
      e.preventDefault(); 
      alert ("This Promotion matches one or more products already associated to this Group. If you continue the existing Promotion will be cancelled and replaced with the currently selected Promotion!"); 
} 
return true; 
}); 

我打開通過比較字符串和返回匹配或任何真正的事情來做到這一點。我對Jquery很新奇。提前致謝。

回答

2
$.each($('#new_products').val().split(''), function(i, char) { 
    var existing = $('#existing_products').val(); 

    if (existing.indexOf(char) != -1) 
     alert('mathces found'); 
}); 

檢查是否有任何從#new_product返回值的字符在從#existing_products返回的值存在?

+2

你不能對'.split()'的結果調用'.each()'。你的意思是'.forEach()'?還是你的意思是使用'$ .each'來代替? – Ian 2013-05-03 21:31:56

+0

@Ian - 我的意思是$。每個,感謝您的注意! – adeneo 2013-05-03 21:35:41

+0

美麗,非常感謝你。現在像冠軍一樣工作。我一直在使用它,因爲像下午2點東部時間:(。+1爲更正哈哈。我就像爲什麼......不會......這個......工作?!?!?! – kyle 2013-05-03 21:40:48