How Do I Use Javascript To Prevent Form Submission Because Of Empty Fields?
How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is 'form' and the input name is 'name'. I have
Solution 1:
HTML Code :-
<formname='form'><inputtype="button"onclick="runMyFunction()"value="Submit form"></form>
Javascript Code :-
functionrunMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Solution 2:
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an &&
operator in the if statement and add the same syntax for OtherFieldName
functioncheckForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
returnfalse;
}
else
{
form1.submit();
returnfalse;
}
}
Solution 3:
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function(event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function(event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
returnfalse;
}
}
}, false);
};
Solution 4:
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
functioncheckForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}
Post a Comment for "How Do I Use Javascript To Prevent Form Submission Because Of Empty Fields?"