Unable to stop form from submitting with empty inputs - javascript

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");
}
}

Related

How to prevent form from sending when there are alerts showing? JavaScript

I created a contactus form on my website, and I have few js functions that check if the values are valid or not. What currently happens is - the functions do work, they check what they are supposed to, and the alert shows as well - But after all the alerts showed, it still submits the form.
I tried to use the Prevent method, and the window.back.history but none worked...
How can I fix it?
JavaScript part:
<script>
function validateForm1() {
var firstname = document.forms["contactus"]["fname"].value;
if (firstname == "") {
alert("Please provide your first name");
return false;
e.preventDefault();
window.history.back();
}
}
document.getElementById("gender").addEventListener('click',checkradio);
function checkradio() {
if(document.getElementById("genderm").checked == false && document.getElementById("genderf").checked == false && document.getElementById("gendero").checked == false ){
alert("Please select your gender");
return false;
e.preventDefault();
window.history.back();}
}
function checkbox(){
if (document.querySelector('#cbr:checked') == null){
alert("Please choose a subject");
return false;
e.preventDefault();
window.history.back();
}
function agecheck(){
var x = document.forms["contactus"]["age"].value;
var y = 18;
if(x<y)
{
alert("Please submit the form only if you're 18 yo");
return false;
e.preventDefault();
window.history.back();
}
}
}
</script>
My HTML part uses the submit method and links to:
<form id="contactus" name="contactus" action="http://jkorpela.fi/cgi-bin/echo.cgi" onsubmit="validateForm1();checkbox();checkradio();agecheck()" style="float:right;text-align: right; direction: rtl;">
I think you can put 'return' in 'onsubmit'.
<script>
function validateForm1() {
var firstname = document.forms["contactus"]["fname"].value;
if (firstname == "") {
alert("Please provide your first name");
return false;
}
if (document.getElementById("genderm").checked == false && document.getElementById("genderf").checked == false && document.getElementById("gendero").checked == false) {
alert("Please select your gender");
return false;
}
if (document.querySelector('#cbr:checked') == null) {
alert("Please choose a subject");
return false;
}
var x = document.forms["contactus"]["age"].value;
var y = 18;
if (x < y) {
alert("Please submit the form only if you're 18 yo");
return false;
}
}
</script>
<form id="contactus" name="contactus" action="http://jkorpela.fi/cgi-bin/echo.cgi" onsubmit="return validateForm1();" style="float:right;text-align: right; direction: rtl;"></form>
In your form for each you can use the required tag so they always have to input something into the field.
For example
<input type="text" id="username" name="username" required>

Validating dynamically created div using jquery

I am adding div dynamically with having multiple input tag to a div having id="lessonDetails". I am trying to validate it with jquery, code is as below :
html:
<div id="lessonDetails">
<div class="greenshades">
<input name="addlesson"/>
<input name="addsubject"/>
</div>
<div class="greenshades">
<input name="addlesson"/>
<input name="addsubject"/>
</div>
<div class="greenshades">
<input name="addlesson"/>
<input name="addsubject"/>
</div>
</div>
<input type="button" onclick="validate()"/>
jquery:
function validate() {
if ( $('#lessonDetails').children().length > 0 ) {
$('#lessonDetails').children().each(function(){
$(this).each(function() {
$('input[name="addlesson"]').each(function() {
if($(this).val() == "") {
alert("Please enter lesson title.");
return false;
}
});
$('input[name="addsubject"]').each(function() {
if($(this).val() == "") {
alert("Please enter subject.");
return false;
}
});
});
});
}
}
It's not working correctly. It gives more than one alert at time.
You don't need multiple each(), Modify the validate function as
function validate() {
var valid = true;
$('#lessonDetails input[name="addlesson"]').each(function() {
if ($(this).val() == "") {
alert("Please enter lesson title.");
valid = false;
return false; //break loop only
}
});
return valid;
}
Use the return value
<input type="button" onclick="return validate()"/>
$(this).each( doesn't makes any sense.
$('#lessonDetails').find('input[name="addlesson"]').each(function () {
if ($(this).val() == "") {
alert("Please enter lesson title.");
return false;
}
});
I am finding all the nested 'input[name="addlesson"]' and iterating over them, rest of the logic is same so this will do the trick.

Html Form If statement in OnSubmit Field

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()">

Should I validate my form twice?

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>

Javascript alert on submit if text field is empty

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');
}
});

Categories

Resources