2015-05-17 193 views
1

點擊我的按鈕後,我會檢查我的文本字段是否爲空。我的支票工作,但如果我顯示我的消息它顯示幾秒鐘。可能是我點擊按鈕的時間。這是我嘗試過的一些代碼。點擊按鈕後顯示錯誤Javascript

<form> 
    <div id="errorblock"> 
     <p id="errortext">Error.</p> 
    </div> 
    <!-- here are my input fields--> 

    <button>Send</button> 
</form> 

這是我加入我的事件偵聽器的頁面初始化後:

document.getElementsByTagName("button")[0].addEventListener("click", function(){ 
    sendEmail(); 
}); 

function sendEmail() { 

    //check if all fields are fill in. If not do this code; 
    document.getElementById("errortext").innerHTML = "Fill in all the fields please."; 

    var errorblock = document.getElementById("errorblock");  
    errorblock.style.visibility = "visible"; 
    errorblock.style.height = "46px"; 
} 

誰能幫助我? 謝謝

回答

4

默認HTMLButtonElementtype="submit"。這意味着在按鈕上點擊表格就會被提交。您需要確保您在表單中出現錯誤的情況下阻止提交。例如通過調用事件對象的preventDefault方法:

document.getElementsByTagName("button")[0].addEventListener("click", function (e) { 
    if (!sendEmail()) { 
     e.preventDefault(); 
    } 
}); 

function sendEmail() { 

    //check if all fields are fill in. If not do this code; 
    document.getElementById("errortext").innerHTML = "Fill in all the fields please."; 

    var errorblock = document.getElementById("errorblock"); 
    errorblock.style.visibility = "visible"; 
    errorblock.style.height = "46px"; 

    // if there are errors return false 
    // return true if input is correct 
    return false; 
} 

此外,我建議聽的形式,而不是按鈕單擊事件上onsubmit事件:

document.querySelector("form").addEventListener("submit", function (e) { 
    if (!sendEmail()) { 
     e.preventDefault(); 
    } 
});