2015-04-23 48 views
1

之前有沒有無論如何要檢查是否有類似的價值在輸入框中存在類似值檢查表單提交

EX:

<form> 
    USER 1 
    <input name="user1" value="bla1"> 
    <input name="pass1" value="ple1"> 
    <input name="email1" value="[email protected]"> 

    USER 2 
    <input name="user2" value="bla2"> 
    <input name="pass2" value="ple1"> 
    <input name="email2" value="[email protected]"> 

    USER 3 
    <input name="user3" value="bla1"> 
    <input name="pass3" value="pla3"> 
    <input name="email3" value="[email protected]"> 

    <button type="submit"> 
</form> 

驗證表單提交時會觸發,它會提醒用戶併爲具有相似值的輸入添加一個類。所有輸入字段都以空白開始,用戶應該輸入值。所有字段只能與其類型USER,PASS和EMAIL進行比較。

+0

您使用PHP或JavaScript ???,你可以使用如果一方......如果(第1項== ITEM2)語句,我不知道爲什麼你需要這份表格{然後警報東西} – Careen

+0

。目的是什麼? – lv0gun9

+0

@YauheniLeichanok爲(VAR計數器= 1;計數器<= $( '#反用戶')VAL();計數器++){ \t \t \t \t X = 1個 \t \t \t \t \t而(X <= $ ( '#反用戶')。VAL()){ \t \t \t \t \t \t \t \t \t \t \t \t如果(計數器!= X){ \t \t \t \t \t \t \t \t \t \t \t \t \t \t如果($( '輸入[名稱= 「用戶 '+計數器+」']')。VAL()= $( '輸入[名稱=「用戶' + X + ' 「] ')VAL()){ \t \t \t \t \t \t \t \t $(' 輸入[名稱=」 用戶' +計數器+「 '] ')addClass(' 驗證失敗的')。 \t \t \t \t \t \t \t \t $( '輸入[名稱= 「用戶 '+ X +」']')。addClass( '驗證失敗的'); \t \t \t \t \t \t \t} \t \t \t \t \t \t \t \t \t \t \t \t \t \t} \t \t \t \t \t \t X ++; \t \t \t \t \t \t警報(X) \t \t \t \t \t} \t \t \t \t \t \t \t \t \t \t \t \t \t} – Link

回答

1

我已經爲您製作了一個小型jsfiddle

基本上它只是遍歷表單中的每個元素,找到任何具有相似名稱的任何元素,並且如果它們具有相同的值,則會將它們標記爲兩者。這比A低一點,B低一點,但仍然效果不錯。

$('form').submit(function(event) { 
    var ok = true, 
     $form = $(this), 
     $inputs = $(this).find('input') 
    $inputs.removeClass('error') 
    $inputs.each(function() { 
     var $src = $(this) 

     //Get the name of the element, and strip off the number 
     var name = $(this).attr('name').replace(/[0-9]/g,'') 

     //Filter the inputs down to only the ones whose name starts the same 
     $inputs.not(this).filter('[name^="' + name + '"]').each(function() { 
      if($src.val() == $(this).val()) { 
       ok = false 
       $(this).addClass('error') 
       $src.addClass('error') 
      } 
     }) 
    }) 
    if(!ok) event.preventDefault() 
})