2013-01-18 69 views
3

我寫了一個基本的表單驗證腳本,現在我試圖重置在用戶沒有填寫必填字段時發生的錯誤。當一個複選框被選中時,從標籤中刪除類

對於複選框和單選按鈕,我已經添加了類error他們的標籤。造成這種情況的HTML代碼如下所示:

<input class="required" id="Example31" name="Example3" type="checkbox" /> 
<label for="Example31" class="error">Example Input 3 Option 1</label> 

<input class="required" id="Example32" name="Example3" type="checkbox" /> 
<label for="Example32" class="error">Example Input 3 Option 2</label> 

<input class="required" id="Example4" name="Example4" type="radio" /> 
<label for="Example4" class="error">Example Input 4</label> 

要添加的錯誤,我計算出,如果具有相同名稱的任何複選框被選中,使用這個腳本:

$("input.required").each(function() { 
    // check checkboxes and radio buttons 
     if ($(this).is(":checkbox") || $(this).is(":radio")) { 
      var inputName = $(this).attr("name"); 
      if (!$("input[name=" + inputName + "]").is(":checked")) { 
       var inputId = $(this).attr("id"); 
       $("label[for=" + inputId + "]").addClass("error"); 
       error = true; 
      }; 
     }; 
    // end checkboxes and radio buttons 
}); 

如何刪除錯誤而不必修改HTML?我正在畫一個完整的空白。下面是我在想什麼:

  1. 圖出與有錯誤
  2. 找到具有該ID的複選框或單選按鈕,每個標籤相關聯的名稱
  3. 找出複選框或單選按鈕命名
  4. 查找複選框或單選按鈕具有相同名稱的其餘部分
  5. 查找這些輸入標識
  6. 查找標籤與這些名字
  7. 克麗r是錯誤關閉這些標籤

我一件T虧損的,雖然。如果任何人都可以幫助,那將不勝感激。

+0

你是不是想立刻從所有標籤刪除錯誤? – ATOzTOA

+0

當你需要刪除的錯誤?當'複選框'是'未選中'? – ATOzTOA

+0

當它成爲檢查。對不起,我一發布這個,就出去吃午飯。我會在幾分鐘內測試下面的錯誤代碼。 – JacobTheDev

回答

0

我能夠解決它自己使用此:

$("input.required").each(function() { 
    if ($(this).is(":checkbox") || $(this).is(":radio")) { 
     var inputName = $(this).attr("name"); 
     var labelFor = $(this).attr("id"); 
     $(this).click(function() { 
      $("input[name=" + inputName + "]").each(function() { 
       var labelFor = $(this).attr("id"); 
       $("label[for=" + labelFor + "]").removeClass("error"); 
      }); 
     }); 
    }; 
}); 
0

我已經將您的「思考」爲代碼。看看這對你的作品...

// Figure out the name associated with each label that has an error 
$(".error").each(function() { 
    var m = $(this).attr('for'); 

    // Find the checkbox or radio button that has that ID 
    $("input[id=" + m + "]").each(function() { 

     // Figure out the checkbox or radio buttons name 
     var n = $(this).attr('name'); 

     // Find the rest of the checkboxes or radio buttons with the same name 
     $("input[name=" + n + "]").not(this).each(function() { 

      // Find those inputs IDs 
      i = $(this).attr('id'); 

      // Find labels with those names 
      $("label[for=" + i + "]").each() { 

       // Clear the errors off of those labels 
       $(this).removeClass("error"); 
      }); 
     }); 
    }); 
}); 
+0

它給了我一個錯誤在最後'''說'未捕獲的SyntaxError:意外的令牌}' – JacobTheDev

+0

更新代碼... – ATOzTOA

相關問題