How prevent submit if input are empty with javascript - javascript

I have a login form but I wanna check if the fields are empty then do not submit. I did `return false' on submit but the browser still loads a new page. How can I stop that?
JS:
var username = document.getElementById('usernameField');
var password = document.getElementById('passwordField');
var loginBtn = document.getElementById('loginBtn');
var infoBox = document.getElementById('formInfo');
var isEmpty = /^\s*$/;
var addEventTo = function(id, type, fn, capture) {
if (document.addEventListener) {
id.addEventListener(type, fn, capture);
} else {
id.attachEvent('on'+type, fn);
}
};
function checkIfAllEmpty() {
var loginForm = document.getElementById('loginform'),
allInputs = loginForm.getElementsByTagName('input'),
max = allInputs.length,
i;
for (i = 0; i < max; i++) {
if (allInputs[i].type !== 'submit') {
if (allInputs[i].match(isEmpty)) {
infoBox.innerHTML = 'All your fields are empty';
return false;
}
}
}
}
//addEventTo(loginBtn, 'click', checkIfAllEmpty, false);
if (document.addEventListener) {
loginBtn.addEventListener('submit', checkIfAllEmpty, false);
} else {
loginBtn.attachEvent('onsubmit', checkIfAllEmpty);
}
HTML:
<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
<fieldset id="loginFieldset">
<legend>Sign in</legend>
<ol>
<li>
<label for="usernameField">Username</label><input type="text" placeholder="Enter username" id="usernameField" />
<span>Please type in your username</span>
</li>
<li>
<label for="passwordField">Password</label><input type="password" placeholder="Enter password" id="passwordField" />
<span>Please type your password</span>
</li>
<li>
<input type="submit" value="Sign in" id="loginBtn" />
</li>
</ol>
</fieldset>
</form>
Many thanks

If it ok to go with html5 (works fine with newer versions of Safari, Chrome, Firefox, Opera > 11.00 but no IE as usual), you can add the required tag in your input field.
<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
<fieldset id="loginFieldset">
<legend>Sign in</legend>
<ol>
<li>
<label for="usernameField">Username</label>
<input type="text" placeholder="Enter username" id="usernameField" required />
<span>Please type in your username</span>
</li>
<li>
<label for="passwordField">Password</label>
<input type="password" placeholder="Enter password" id="passwordField" required />
<span>Please type your password</span>
</li>
<li>
<input type="submit" value="Sign in" id="loginBtn" />
</li>
</ol>
</fieldset>

Looks like the event listener of the onsubmit are not being added correctly, anyway the easiest way to do it is to add onsubmit="return someValidationFuncThatReturnTrueOrFalse()" in your form:
<form id="loginForm" method="post" action="#" onsubmit="return validate()">
can I ask why you're using this approach on your js code? it could be done much easily if your form is static ...
function validate() {
if (document.getElementById("usernameField").value == "" && document.getElementById("usernameField").value == "") {
alert("all fields are empty");
return false;
} else {
return true;
}
}
or something like that ...

You can use the attribute disabled="disabled" for the form inputs :
http://www.w3schools.com/tags/att_input_disabled.asp
set the submit button as disabled, then add an onchange listener to each input field so that if every field is filled you remove the disable attribute and the user can subit the form.

I use Prototype (as a javascript framework) and this code should work:
js:
function checkEmpties() {
var usr = $('username');
var pass = $('pass');
var frm = $('formId');
if (usr.value && pass.value) {
//frm.submit();
alert('submit');
} else {
alert('failed');
}
}
Event.observe(window, 'DomReady', function() {
var btn = $('submitBtn');
Event.observe('submitBtn', 'click', checkEmpties);
}
html:
<form id="formId">
<input type="text" name="username" id="username" />
<input type="password" name="pass" id="pass" />
<input type="button" id="submitBtn" value="Send" />
</form>
What it does:
Once the document has loaded attaches an event observer to the button, so when it's clicked the function checkEmpties is called.
This function will retrieve the value of the inputs and if they're not empty, submit the form.
Hope it helps

Related

Using JavaScript to check for user-input

I'm submitting a form with input text to my server through my web client. What I'm trying to do is to check whether the user has passed in text into the input field before sending the form by hitting the submit button.
What I have tried so far:
var form = document.getElementById("id");
document.getElementById("id").addEventListener("click", function() {
var input = document.getElementById("content").value;
if (input == "") {
alert("write something in the textfield");
} else {
form.submit();
}
});
<form action="" method="post" id="id">
<input type="text" name="name" id="content">
<button type="submit" id="submit-id">submit text</button>
</form>
Any good tips on how to do this?
You want preventDefault on the submit event
document.getElementById("id").addEventListener("submit", function(e) {
const input = document.getElementById("content").value;
if (input.trim() === "") {
alert("write something in the textfield");
e.preventDefault()
}
});
<form action="" method="post" id="id">
<input type="text" name="name" id="content">
<button type="submit" id="submit-id">submit text</button>
</form>
Alternatively just add required attribute - no need for script:
<form action="" method="post" id="id">
<input type="text" name="name" id="content" required>
<button type="submit" id="submit-id">submit text</button>
</form>
you can use the simple code snippet instead :
<form action="" method="post" id="id">
<input type="text" name="name" id="content" required>
<button type="submit" id="submit-id">submit text</button>
</form>
function submitIt(e) {
var formData = new FormData(e);
var object = {};
formData.forEach(function(value, key) {
object[key] = value;
});
if (object.name == "") {
alert("null");
} else {
alert("ok");
return true;
}
return false;
}
<form onsubmit="return submitIt(this)">
<input type="text" name="name">
<button>submit text</button>
</form>

Show alert (Text Field is empty) on submit Html/JavaScript

How to get an Alert on Submit when I left a TextBox empty And It Should Turn To the Next page on submit.
Must Reply,
Thank You.
You can try this :
HTML :
<form action="" method="POST" id="myForm">
<input id="myInput" type="text" />
<input type="submit" />
</form>
(Replace the action attribute by the url of your destination page, the one you call the "next page").
JS (without jQuery):
var myForm = document.querySelector('#myForm');
var myInput = document.querySelector('#myInput');
myForm.addEventListener('submit', function(pEvent) {
if(myInput.value === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
//Do whatever you want
}
});
JS (with jQuery) :
var myForm = $('#myForm');
var myInput = $('#myInput');
myForm.on('submit', function(pEvent) {
if(myInput.val() === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
}
});
Demo : http://jsfiddle.net/af9qvkmp/9/
Here is the demo, based on jQuery!
HTML
<form action="" method="POST" id="form">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="input3" type="text" />
<input id="input4" type="text" />
<input id="input5" type="text" />
<input type="submit" />
</form>
JS
$(function() {
$('#form').on('submit', function(event) {
var isError = false;
$(this).find('input[type="text"]').each(function() {
if($(this).val() == '') {
console.log($(this));
isError = true;
return false;
}
});
if(isError) {
event.preventDefault();
alert("Got Error");
} else {
// Submit the form
}
});
});
In form tag write
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkform(this);">
This is your input field
<input type="text" name="reviewValue" value="" id='starRate2' required>
Javascript Code:
<script language="JavaScript" type="text/javascript">
function checkform ( form ){
if (form.reviewValue.value == "") {
alert( "Please choice your Rating." );
form.reviewValue.focus();
return false ;
}
return true ;
}
</script>

How to make a required field be invisible if valid?

I have this kind of html:
<form method="post" action="register">
<input type="text" name="name" required />
<button>Next</button>
</form>
When I click the Next button, I want to hide the Name field, but only if it is valid(not empty) and I don't want to submit the form. How can I do this with plain JavaScript?
If you know a way with jQuery, please write that too. Thanks.
Try this:
$('button').click(function() {
var check = $('#name').val();
if (check == '') {
$('#name').hide();
}
})
If the input has no content, it will be hidden.
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault();
var input = e.target.firstElementChild;
if(!input.validity.valueMissing) {
input.style.display = 'none';
}
}, false);
<form method="post" action="register">
<input type="text" name="name" required />
<button>Next</button>
</form>
Assuming that you will change "form button" for the ID of the button, and "form input" for the ID of the input. The jQuery code would be something like this:
$("form button").click(function() {
if ($("form input").val() != "")
$("form input").hide();
});
Try this:
<form method="post" action="register">
<div id="steps1">
<input id="txtname" type="text" placeholder="enter name here" name="name" />
<input id="btnNext" type="button" value="next" />
</div>
<div id="complete" style="display:none;">
<input type="text" name="age" placeholder="enter age here" />
<input type="submit" value="submit" />
</div>
</form>
$(document).ready(function () {
$("#btnNext").click(function () {
if ($("#txtname").val() != "") {
$("#steps1").hide();
$("#complete").show();
}
});
});
In jQuery:
$("button").click(function() {
if ($('input[name=name]').val() != '') {
$('input[name=name]').fadeOut(); // Or hide, or css('display', 'none')
}
});
Make class e.g. "validate", which you can attach to your form after clicking Next.
Then in CSS:
.validate input:valid {
display: none;
}
Try onsubmit event:
var validate = function(form) {
var toSubmit = true;
if (form.name.value) { //has some text
form.name.style.display = "none"; //hide the input field
} else {
toSubmit = false;
}
return toSubmit;
};
<form method="post" action="register" onsubmit='return validate(this);'>
<input type="text" name="name" required />
<button>Next</button>
</form>
EDIT
Try blur event:
var validate = function(box) {
if (!box.value) {
alert('This field is required');
box.focus();
}
};
<form method="post" action="register">
<input type="text" name="name" onblur='validate(this);' />
<button>Next</button>
</form>
Read these to understand the code and why.
document.querySelector
EventTarget.addEventListener
onsubmit
event.preventDefault
Constraint validation HTML5
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault();
var input = e.target.firstElementChild;
if(!input.validity.valueMissing) {
input.style.display = 'none';
}
}, false);
<form method="post" action="register">
<input type="text" name="name" required />
<button>Next</button>
</form>

Validate a form by passing the form name as a constructor

I'm trying to validate a form by passing the form node through a constructor. I know using OO is a bit over the top but it's a request. I've got the code below, but when I try to alert out the values of the text boxes in function(form), they are coming up as undefined.
<SCRIPT LANGUAGE="JavaScript">
function Validator(fields) {
this.fields = fields;
}
Validator.prototype.validate = function (form) {
for (var i = 0, l = this.fields.length; i < l; i++) {
alert(this.fields[i].value);
if (this.fields[i].value == 0) {
alert("The field is empty");
return false;
}
}
}
var validator = new Validator(["username", "password"]);
function runValidate(form) {
validator.validate(form);
}
</SCRIPT>
</head>
<body>
<form NAME="AbbeyRoad">
<fieldset>
<legend>Please login</legend>
<div class="form-element">
<label for="username"><span class="shortkey">U</span>sername:</label>
<input type="text" name="username" id="username" accesskey="u">
</div>
<div class="form-element">
<label for="password"><span class="shortkey">P</span>assword:</label>
<input type="password" name="password" id="password" accesskey="p">
</div>
<input type="button" name="login" value="Login" id="login" onClick="runValidate(this.form)">
</fieldset>
</form>
Change:
alert(this.fields[i].value);
to:
alert(form[this.fields[i]].value);
and this:
if (this.fields[i].value == 0) {
to:
if (form[this.fields[i]].value == 0) {

Form validation with Javascript function

I am trying to validate a form, to make sure that the user inputs a value into a textbox. Here's my Javascript:
var formValidation = function(a) {
if (document.getElementById(a).value == "") {
alert('Please fill out the ' + a + ' field');
return false;
}
else {
return true;
}
}
And here's the form:
<div id="cultdiv">
<form action="add.php" method="POST">
<span><input type="hidden" name="id" id="cultid"/>
<input type="text" onSubmit ="formValidation('culture')" name="name" id="culture"/>
<input type="hidden" name="type" value="culture" />
<input type="submit" value="add/update" /></span>
</form>
</div>
For some reason it doesn't stop the form from being submitted or give the alert message.
You forgot to return from your inline handler.
Also, <input>s don't have an onsubmit event; you probably meant to put that in the <form>.
slaks means something along these lines.
<script>
var formValidation = function() {
if (document.getElementById('culture').value == "") {
alert('Please fill out the culture field');
return false;
}
else {
return true;
}
}
<div id="cultdiv">
<form action="add.php" method="POST" onsubmit="return formValidation(this)">
<span><input type="hidden" name="id" id="cultid"/>
<input type="text" name="name" id="culture"/>
<input type="hidden" name="type" value="culture" />
<input type="submit" value="add/update" /></span>
</form>
</div>

Categories

Resources