Javascript alert on submit if text field is empty - javascript

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

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>

Unable to stop form from submitting with empty inputs

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

enabled button if password match

here is my script
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
enter.disabled = true;
} else if (user_pass == user_pass2 ){
enter.disabled = false;
} else {
enter.disabled = true;
alert("Your password doesn't same");
}
});
this my html
Password : <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
i am really new in Javascript and jQuery, and this is my first using jquery. i need to make a disabled button if the password doesn't match but, after i put the same password the button is still disabled.
$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
//var enter = $("#enter").val();
if (user_pass.length == 0) {
alert("please fill password first");
$("#enter").prop('disabled',true)//use prop()
} else if (user_pass == user_pass2) {
$("#enter").prop('disabled',false)//use prop()
} else {
$("#enter").prop('disabled',true)//use prop()
alert("Your password doesn't same");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Password :
<input type="password" name="user[user_pass]" id="reg_pass" required="required">Confirm password
<input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
Use .prop()
You need to set disable attribute like this in jquery $("#enter").attr('disabled',true);
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").attr('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").attr('disabled',false);
} else {
$("#enter").attr('disabled',true);
alert("Your password doesn't same");
}
The .prop( propertyName, value ) allow you set one or more properties for the set of matched elements.
JS
$(function() {
$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var confirm_user_pass = $("#reg_confirm_pass").val();
var enter = $("#enter");
if (user_pass.length == 0) {
alert("please fill password first");
enter.prop('disabled', true)
}
else if (user_pass == confirm_user_pass) {
enter.prop('disabled', false)
}
else {
enter.prop('disabled', true)
alert("Your password doesn't match");
}
});
});
HTML
Password: <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password: <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
I believe the other answers are right on target. I set up a simple 'jsfiddle' using jquery and its .prop() method to better illustrate here.
NOTE: I would probably bind to another event to make it fire when changes are made to either input element.
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").prop('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").prop('disabled',false);
} else {
$("#enter").prop('disabled',true);
alert("Your password doesn't same");
}
});
Actually blur will not enable the button instantly, keyup eventhandler does the best job. Here's the below code.
$("#reg_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
$("#reg_confirm_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
Here it responds to the changes in either of the text boxes instantly.
Check it here.
Any better solution than this, please let me know. Thank you.

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.

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>

Categories

Resources