Update:
I believe the solution you are seeking involves utilizing the attributes placeholder
, required
, and autofocus
. There is no need for JavaScript to validate if the inputs are empty. Here is an example of how you can set up your form:
<form>
<input id=CompanyName type=text placeholder=CompanyName required autofocus />
<input id=ContactName type=text placeholder=ContactName required />
<input id=Address type=text placeholder=Address required />
<input id=PhoneNumber type=text placeholder=PhoneNumber required />
<input id=Email type=text placeholder=Email required />
<input type=submit value=send />
</form>
After setting up the form, you can perform actions when the form is submitted:
function sendMyForm(event){
alert("Form Submitted Successfully...");
}
var sendForm = document.querySelector("form");
sendForm.addEventListener("submit", sendMyForm, false);
<form>
<input id=CompanyName type=text placeholder=CompanyName required autofocus />
<input id=ContactName type=text placeholder=ContactName required />
<input id=Address type=text placeholder=Address required />
<input id=PhoneNumber type=text placeholder=PhoneNumber required />
<input id=Email type=text placeholder=Email required />
<input type=submit value=send />
</form>
Additionally, you can use the classList
property:
document.querySelector("#CompanyName").classList.add('my');
Your code could be enhanced with this approach:
function check_empty() {
if (document.getElementById('CompanyName').value == "" || document.getElementById('ContactName').value == "" || document.getElementById('Address').value == "" || document.getElementById('PhoneNumber').value == "" || document.getElementById('Email').value == ""){
alert("Fill All Fields !");
} else {
/* Adding a class "my" */
document.querySelector("#CompanyName").classList.add('my');
alert("Form Submitted Successfully...");
}
}