2017-05-01 89 views
1

你好(我無法找到這一個任何類似的問題,如果你請讓我知道),這裏要達到的目標後jQuery的插入HTML是一個元素後插入HTML內容和如果在插入html內容之前將其刪除。 我的代碼現在[部分HTML和JS]元素刪除現有元素

<form method="POST" action="somePage.php"> 
    <input type="text"> 
    <input type="text"> 
    <input type="submit"> 
</form> 
<script> 
    $(document).ready(function(){ 
     $("form").on("submit",function (e){ 
      e.preventDefault(); 
      $(this).find(":text").each(function(){ 
       if($(this).val()==''){ 
        $(this).after("<p class='error'>Please fill this field</p>"); 
       } 
      }); 
     }); 
    }); 
</script> 

的代碼,它的工作,但問題是,如果形式submited不止一次文本更「請填寫此場」顯示多次 我曾經想過把一個跨度(或DIV)每個輸入之後,寫了下面的代碼:

$(this).next("span").html("<p class='error'>Please fill this field</p>"); 

這將是一個解決方案,但一點改進將是我會在每次輸入我想以後寫的跨度驗證並且效率不高。 我想知道一個更好的方式來做到這一點,如果你能告訴我這將是真棒,

回答

1

只是與類錯誤刪除的DOM元素每個表單提交,如時間低於

<form method="POST" action="somePage.php"> 
    <input type="text"> 
    <input type="text"> 
    <input type="submit"> 
</form> 
<script> 
    $(document).ready(function(){ 
     $("form").on("submit",function (e){ 
      e.preventDefault(); 
      : $("form . error").remove(); 
      $(this).find(":text").each(function(){ 
       if($(this).val()==''){ 
        $(this).after("<p class='error'>Please fill this field</p>"); 
       } 
      }); 
     }); 
    }); 
</script> 

這樣所有的錯誤將在點擊提交時被刪除。如果不存在,什麼都不會被刪除

+0

我沒有想過這個問題,聽起來很好的解決方案,如果我有相同的類形式以外的其他元素的問題將得到taht,他們將被刪除,我可以做下一個: $(「form .error」).remove();既然你給了我解決這個問題的關鍵,我會選擇你的答案,謝謝你。 –

2

這樣做的一個方法是刪除所有的錯誤,然後重新進行添加適用的。

$(document).ready(function(){ 
 
    $("form").on("submit",function (e){ 
 
     e.preventDefault(); 
 
     $("p.error").remove(); 
 
     $(this).find(":text").each(function(){ 
 
      if($(this).val()==''){ 
 
       $(this).after("<p class='error'>Please fill this field</p>"); 
 
      } 
 
     }); 
 
    }); 
 
});
input { 
 
    display:block; 
 
    margin-top:20px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form method="POST" action="somePage.php"> 
 
    <input type="text"> 
 
    <input type="text"> 
 
    <input type="submit"> 
 
</form> 
 
<script> 
 

 
</script>