My code works perfectly here.
But the problem is that I want to add some code validation so that the form can't be submitted if something is wrong in the code. Here is the code I added:
Jquery code:
var user = document.getElementById('u');
var email = document.getElementById('em');
var pass1 = document.getElementById('p1');
var pass2 = document.getElementById('pa2');
function isEmpty(input) {
if (input.value == "" || input.value == null) {
return true;
} else {
return false;
}
}
function validateform() {
if(isEmpty(user) || isEmpty(email) || isEmpty(pass1) || isEmpty(pass2))
{
alert("All fields are required.");
$("#form").submit(function(event) {
event.preventDefault();
});
if(isEmpty(user))
{
user.focus();
}
else if(isEmpty(email))
{
email.focus();
}
else if(isEmpty(pass1))
{
pass1.focus();
}
else if(isEmpty(pass2))
{
pass2.focus();
}
}
}
I also added an Id to my form:
<form action="m.php" method="post" id="form">
I also added the onsubmit here:
<input name="submit" type='submit' value='Submit' onsubmit="validateform()">
but it is not working, the page just moves to m.php even if all fields are empty. what should I do? should I install the jquery validating plugin and validate twice?
Edit
Here is a Demo
After you check if the field is empty if you return false; then the from will not submit.
Form on submit example.
JavaScript
function validateform() {
if(isEmpty(user))
{
user.focus();
return false;
}
else if(isEmpty(email))
{
email.focus();
return false;
}
else if(isEmpty(pass1))
{
pass1.focus();
return false;
}
else if(isEmpty(pass2))
{
pass2.focus();
return false;
}
}
Your onsubmit needs to be on your form not your button.
HTML
<form action="m.php" method="post" id="form" onsubmit="validateform()">
<input name="submit" type='submit' value='Submit' >
Don't need to validate twice.
JS:
function isEmpty(input) {
return $.trim(input.value) == "";
}
function validateform() {
var user = document.getElementById('u');
var email = document.getElementById('em');
var pass1 = document.getElementById('p1');
var pass2 = document.getElementById('pa2');
if(isEmpty(user) || isEmpty(email) || isEmpty(pass1) || isEmpty(pass2))
alert("All fields are required.");
if(isEmpty(user)){
user.focus();
return false;
}else if(isEmpty(email)){
email.focus();
return false;
}else if(isEmpty(pass1)){
pass1.focus();
return false;
}else if(isEmpty(pass2)){
pass2.focus();
return false;
}
return true;
}
$('form#myForm').submit(function(e){
e.preventDefault();
if( validateform() ) //just validate once!
this.submit(); //and then submit once;
return false;
});
HTML:
<form action="m.php" method="post" id="myForm">
.....
......Other form settings....
.....
<input name="submit" type='submit' value='Submit'>
</form>
Related
I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
There is a form, where on submission the new page is opened, only in case if validation is ok. However, the window is opened in every case, and I guess that validation isnt working, while it is supposed to...
I would appreciate if you could point me to the right direction.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function overallcheck() {
if (!checkjob() || !checkEmail() || !Checkname()) {
writeTo("problemArea", "Error messages area");
return false;
}
if (!Checkname()) {
writeTo("problemArea", "Please inser a valid name");
return false;
}
if (!checkEmail()) {
writeTo("problemArea", "Please inser a valid email");
return false;
}
if (!checkjob()) {
writeTo("problemArea", "Please inser your job");
return false;
}
elsereturn true;
}
function Checkname() {
clearElement("problemArea");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname))
return false;
}
function checkEmail() {
clearElement("problemArea");
var mail = document.forms['form'].Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1)
return false;
}
}
function checkjob() {
clearElement("problemArea");
var i;
for (i = 0; i < 4; i++) {
if (document.forms['form'].job[i].checked) {
return true;
}
}
return false;
}
//-->
</script>
</head>
<body>
<form onsubmit=( "return overallcheck();") action="another.html" id=form target="_blank" method="GET">
<table>
<button type="submit" onclick="">submit</button>
</form>
</body>
</html>
Well... That's invalid JavaScript. As NewToJS noted in his comment, elsereturn true; is not correct.
You need to use:
else {
return true;
}
Also, this (onsubmit=( "return overallcheck();")) won't work. You need to do this:
<form onsubmit="return overallcheck();" action="another.html" id="form" target="_blank" method="GET">
I'm fairly new to html/php/js and I'm running into an issue when conditionally submitting my form. Basically, what Im trying to do is have it where the confirm('Do you want to submit this form?') function only shows up if every field has a value entered (the checkform() function). If both are true, then the form will submit. Any help would be greatly appreciated, thanks!
<script type="text/javascript">
function checkform()
{
var myForm=document.frmhot;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
return false;
myForm.status.focus();
}
if (myForm.line.value==""){
alert("Please select a line.");
return false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
return false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
return false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
return false;
}
return true;
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot"
onclick="if(checkform();){
confirm('Do you want to submit the form?');
}
>
<input class="button_text" type="submit" value="Submit" name="submit" onclick= "checkform();" />
</form>
Complete working solution with corrections and tweaks for IE compatibility to a certain extend.
<script>
function checkform(evt) {
var myForm = document.frmhot;
var condition = true;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
myForm.status.focus();
condition = false;
}
if (myForm.line.value==""){
alert("Please select a line.");
condition = false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
condition = false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
condition = false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
condition = false;
}
if(condition){ condition = confirm('Do you want to submit the form?'); }
if(!condition) {
if(evt.preventDefault) { event.preventDefault(); }
else if(evt.returnValue) { evt.returnValue = false; }
else { return false; }
}
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot" onsubmit="checkform(event)">
<input type="text" name="status"/>
<input type="text" name="line"/>
<input type="text" name="reason"/>
<input type="text" name="partnum"/>
<input type="text" name="badgescan"/>
<input class="button_text" type="submit" value="Submit"/>
</form>
You have the right idea, just extract your code into its own function and then call that in the onclick.
Add this function:
function checkAndConfirm() {
if(checkform()) {
if (confirm('Do you want to submit the form?')) {
// submit the form
}
}
And then call it from the onclick attribute:
<form method="post" action="newhotpartgenerate.php" name="frmhot" onclick="checkAndConfirm()">
So i want to alert the user if they submit the form with an empty text field
HTML:
<form id="orderform">
<input type="text" name="initials" id="initials" maxlength="3">
<p class="center">
<input type="image" src="#" id="submitbutton" name="submit" value="Place Order">
</p>
</form>
Javascript:
$('#orderform').submit(function() {
if($('#initials').length == 0){
alert('Please fill out your initials.');
}
});
Just make sure you return false in there somewhere-
$('#orderform').submit(function() {
if($('#initials').val() == ''){
alert('Please fill out your initials.');
return false;
}
});
$('#initials').length will check if the element exists. Try this:
$('#orderform').submit(function() {
if($('#initials').val().length == 0){
alert('Please fill out your initials.');
}
});
as lewsid pointed out, you should also return false if you want to cancel the submit
$('#orderform').submit(function(e) {
e.preventDefault();
if(!$.trim((this + ' input').val()).length){
alert('Please fill all the fields');
return false;
}
return true;
});
but is better if you do this with pure JS not jQuery
function funnjsTrim(input) {
return input
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '')
.replace(/([\s]+)/g, '-');
}
validate_form = function(form, mssg){
mssg = form_errors[mssg] || 'Error: empty field';
var form_to = form.name,
elems = document.forms[form_to].getElementsByTagName("input");
for(var i = 0; i < elems.length + 1; i++) {
if(elems[i].type != 'submit') {
var string = funnjsTrim(elems[i].value);
if(!string.length) {
alert(mssg);
error = 'error';
return false
}
}
}
if(typeof error == "undefined"){
alert('Valid');
return true;
}
}
so in your html
<form onsubmit="return validate_form(this)">
in this line: if(elems[i].type != 'submit') add || elems[i].class != 'your input class' to add exceptions
I'd use e.preventDefault() instead of return false. Return false also prevents events from bubbling and can have unintended consequences if you don't understand this. Also nest that preventDefault within your if, no reason to stop submission if things are good.
$('#orderform').submit(function(e) {
if(!$.trim($(this).find('input[type="text"]').val()).length){
e.preventDefault();
alert('Please fill all the fields');
}
});
For an assignment I have I am writing a registration form. My question is how would I connect the first statement, and the function below so when someone types in their email in the text box it checks to see if the email is valid? (document.getElementById('user').value)
<input id="user" type="text" onblur="isUserNameValid();"></input><br/>
function isEmailValid(email) {
"use strict";
var e = email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[\w.-]/;
if (e.length !== 2) {
return false;
}
if (local.test(e[0])) {
return false;
}
if (e[0].length > 253) {
return false;
}
if ((e[0][0] === ".") || (/\.\./.test(e[0]))) {
return false;
}
if (domain.test(e[1])) {
return false;
}
if (e[1].length > 253) {
return false;
}
if (e[1][0] === "." || /\.\./.test(e[1]) || e[1][e[1].length - 1] === ".") {
return false;
}
return true;
}
As you confirmed you can use HTML5, simply change your input to the below and the browser will validate the email for you when the form is submitted.
<input id="user" name="user" type="email" /><br/>
N.B. You can use a self closing tag for an input. You should also assign the name attribute of the input as that is what is used as the key for the data when it is submitted to the server.
<input type="text" id="email" name="email" onblur="javascript:return validate();"/>
<script>
function validate() {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.getElementById("email").value;
if (reg.test(address) == false) {
alert('Invalid Email Address');
return false;
} else {
alert('valid Email Address');
return false;
}
}
</script>