form onsubmit doesnt work properly - javascript

So I have a login form im making, and I want to test if the inputs are empty or not.
I don't get an error, but when i submit it just ignores the onsubmit.
help?
this is my form:
<form onsubmit="return ifEmpty();" action="login1.php" method="post" id="loginform" accept-charset="UTF-8">
<div style="vertical-align: top;" dir="rtl">
<label dir="rtl" class="labels">שם משתמש/אימייל</label>
<br>
<br>
<input name="unameemail" id="username" type="text">
</div>
<div style="display: block;vertical-align:top;" dir="rtl">
<br>
<label dir="rtl" class="labels">סיסמה</label>
<br>
<br>
<input name="password" id="passwordin" type="password">
</div>
<div>
<br>
<br>
<br>
<input class="btn" type="submit" name="submitone" onclick="" value="login">
</div>
</form>
</div>
and my js:
<script type="text/javascript">
function ifEmpty() {
if (document.getElementById("username") == "") {
document.getElementById("username").style.backgroundColor = "red";
document.getElementById("username").style.color = "white";
document.getElementById("username").className += " invalidform";
return false;
} else if (document.getElementById("passwordin") == "") {
document.getElementById("username").style.backgroundColor = "white";
document.getElementById("username").style.color = "black";
document.getElementById("password").style.backgroundColor = "red";
document.getElementById("password").style.color = "white";
document.getElementById("password").className += " invalidform";
return false;
}
}
</script>

if (document.getElementById("username") == "") {
You are comparing DOM elements to strings here ;-)
You need to access the value property of the input elements.

Change:
if (document.getElementById("username") == "") {
to this:
if (document.getElementById("username").value == "") {

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>

Inserting regular expression for verifying URL address and email address

I need to insert a regular expression to verify the input for URL and email is valid, so where would this go in the code to make it work without messing with anything else? I need to know exactly where it would go and how it would look.
window.onload = function() {
document.getElementById('ifBusiness').style.display = 'none';
}
function BusinessorResidence() {
var is_business = document.getElementById('businessCheck').checked;
if (is_business) {
document.getElementById('ifBusiness').style.display = 'block';
document.getElementById('ifResidence').style.display = 'none';
} else {
document.getElementById('ifBusiness').style.display = 'none';
document.getElementById('ifResidence').style.display = 'block';
}
}
function validateForm() {
var is_business = document.getElementById('businessCheck').checked;
var address = document.forms["myForm"]["address"];
var bname = document.forms["myForm"]["bname"];
var url = document.forms["myForm"]["url"];
var tax = document.forms["myForm"]["tax"];
var rname = document.forms["myForm"]["rname"];
var email = document.forms["myForm"]["email"];
// Address always has to be checked
if (address.value == "") {
alert("Please enter an address.");
address.focus();
return false;
}
// Check the bname, tax and url if a business is selected
if (is_business) {
if (bname.value == "") {
alert("Please enter a business name.");
// focus() is a method, not a property, so you need to call this function to actually focus the text input.
bname.focus();
return false;
}
if (tax.value == "") {
alert("Please enter a business tax ID.");
tax.focus();
return false;
}
if (url.value == "") {
alert("Please enter a business URL.");
url.focus();
return false;
}
}
// Else check the rname and the email
else {
if (rname.value == "") {
alert("Please enter a residence name.");
rname.focus();
return false;
}
if (email.value == "") {
alert("Please enter an email address.");
email.focus();
return false;
}
}
// Open the popup window.
// _blank refers to it being a new window
// SELU is the name we'll use for the window.
// The last string is the options we need.
var popup = window.open('', 'SELU', 'toolbar=0,scrollbars=0,location=0,statusb ar=0,menubar=0,resizable=0,width=400,height=400,left=312,top=234');
// Set the form target to the name of the newly created popup.
var form = document.querySelector('form[name="myForm"]');
form.setAttribute('target', 'SELU');
return true;
}
head {
text-align: center;
}
body {
text-align: center;
}
.bold {
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h1>Fill the form below</h1>
<!-- center tag is deprecated and should be replaced by CSS -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="text" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="text" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
<hr>
<hr>
</body>
</html>
To validate whether or not a user is inputting an url/email, simply change your input type to "url" or "email" and it will be validated for you.
Like so:
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="url" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="email" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>

Javascript Validation form onsubmit not returning false

Note : i searched similar questions and still couldn't fix it so i'm asking again.
i have a form and its onsubmit = "return submit()". it checks if textarea is empty. If it is then it returns false but that doesn't work.The action still goes to the next website even if text area is empty.
let firstName = document.querySelector('#firstname');
let lastName = document.querySelector('#lastname');
let password = document.querySelector('#password');
let retypePass = document.querySelector('#repassword');
let radioMale = document.querySelector('#male');
let radioFemale = document.querySelector('#female');
let textArea = document.querySelector('#textarea');
let select= document.querySelector('#select');
let button = document.querySelector('#button');
let form = document.querySelector('#form');
function submit(){
if (textArea.value = "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
HTML :`
<div class='wrapper'>
<h1>Registration Form</h1>
<form action="http://google.com" id='form' onsubmit="return submit()">
<input placeholder="First Name" type="text" id='firstname' required>
<span></span>
<br>
<input placeholder="Last Name" type="text" id='lastname' required>
<span></span>
<br>
<input placeholder="Password" type="text" id='password' required>
<span></span>
<br>
<input placeholder="Retype Password" type="text" id='repassword' required>
<span></span>
<br>
<input placeholder="Phone Number" type="tel" id='tel' >
<br>
<div class='radio'>
<h4>Selector Your Gender</h4>
<input type='radio'name='same' id='male'>Male
<input type='radio'name='same' id='female'>Female
</div>
<p style="margin:5px 0px;color:white">ADDRESS:</p>
<textarea id='textarea'></textarea>
<span></span>
<p style="margin:5px 0px;color:white">Country:</p>
<select type='country' style="width:84%" id='select'>
<option>England</option>
<option>Japan</option>
<option>America</option>
<option>France</option>
<option>NetherLands</option>
</select>
<br><br>
<input type='submit' value='submit'>
</form>
</div>
Your if systax was wrong:
if (textArea.value = "")
It should be:
if (textArea.value == "")
You must change the name of the function
Example
<form action="http://google.com" id='form' onsubmit="return validate()">
and
function validate() {
if (textArea.value == "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
try
if (!textArea.value) {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
OR
if (textArea.value == '') {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}

Javascript Error message flashes for only a second [duplicate]

This question already has answers here:
What is the meaning of onsubmit="return false"? (JavaScript, jQuery)
(4 answers)
Closed 5 years ago.
I have this HTML project that validates an empty form. The error is being displayed on the side of the inputs but only flashes for a second. I just want the error of the messages to be displayed once
This is my HTML code with the necessary links:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript - JQuery </title>
<link rel="stylesheet" type="text/css" href="contactform.css">
</head>
<body>
<h1 id="pageheading">Zedland Health Authority</h1>
<h2 class="sectionheading">Contact Form</h2>
<form id="register">
<fieldset id="controls">
<div>
<label class="formlabel" for="fname">First Name: </label>
<input id="fname" type="text" size="30" placeholder="First name"
autofocus>
<p id="fname-error" class="error" style="display:none; color:red;">*
You must enter a first name.</p>
</div>
<div>
<label class="formlabel"for="lname">Last Name: </label>
<input id="lname" type="text" size="30">
<p id="lname-error" class="error" style="display:none; color:red;">*
You must enter a Last name.</p>
</div>
<div>
<label class="formlabel" for="title">Title: </label>
<select id="title">
<option value="Mr">Mr.</option>
<option value="Ms">Ms.</option>
<option value="Mrs">Mrs.</option>
<option value="Miss">Miss.</option>
<option value="Master">Master.</option>
</select>
</div>
<div>
<label class="formlabel" for="heathauthoritynumber"><span>
<img src="tooltip.png" id="qmark" alt="Hint"></span>
Health Authority Number:
</label>
<input id="healthauthoritynumber" type="text" size="10">
<p id="hn-error" class="error" style="display:none; color:red;">*You
must enter a Health Authority Number eg('ZHA345742)</p>
<div class="tooltip" id="ttip">If you do not know your ZHA number
,please contact your GP</div>
</div>
<div>
<label class="formlabel" for="email">Email: </label>
<input id="email" type="text" size="40">
<p id="email-error" class="error" style="display:none; color:red;">You
must enter email</p>
</div>
<div>
<label class="formlabel" for="telephone">Telephone Number: </label>
<input id="telephone" type="text" size="40">
<p id="tele-error" class="error" style="display:none; color:red;">You
must enter a telephone</p>
</div>
<div class="formlabel">
<input id="submit-button" type="submit" value="Submit" >
</div>
</fieldset>
</form>
<script src="contactform.js"></script>
</body>
</html>
This is my Javascript
function onSubmit(){
console.log("ive been submitted");
checkEmpty(document.getElementById('fname'),document.getElementById("fname-error"));
checkEmpty(document.getElementById('lname'),document.getElementById("lname-error"));
checkEmpty(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
checkEmpty(document.getElementById('email'),document.getElementById("email-error"));
checkEmpty(document.getElementById('telephone'),document.getElementById("tele-error"));
//checkValidHealthID(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
}
// Read about regular expressions using: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
// and http://stackoverflow.com/questions/25155970/validating-uk-phone-number-regex-c
function checkValidHealthID(inputID, errorID){
var re = new RegExp('/ZHA\d{6}$/');
if((inputID.value)!== re){
errorID.style.display = "inline";
}else
{
errorID.style.display = "none";
}
}
function checkEmpty(inputID, errorID){
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
console.log("checking empty");
if((inputID.value === "") || (inputID.value.length === 0)){
console.log("empty!!");
errorID.style.display = "inline";
}
else
{
errorID.style.display = "none";
}
}
function textHint(txtElem, defaultText) {
txtElem.value = defaultText;
txtElem.style.color = "#A8A8A8";
txtElem.style.fontStyle = "italic";
txtElem.onfocus = function() {
if (this.value === defaultText) {
this.value = "";
this.style.color = "#000";
this.style.fontStyle = "normal";
}
}
txtElem.onblur = function() {
if (this.value === "") {
this.value = defaultText;
this.style.color = "#A8A8A8";
this.style.fontStyle = "italic";
}
}
}
function textHints() {
//textHint(document.getElementById("firstName"), "Enter your first name");
textHint(document.getElementById('lname'), "Enter your last name");
textHint(document.getElementById('healthauthoritynumber'), "for eg
,ZHA346783");
textHint(document.getElementById('email'), "Enter your email");
textHint(document.getElementById('telephone'), "Enter your telephone
number");
}
function switchToolTip() {
document.getElementById('qmark').onmouseover = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='block';
}
document.getElementById('qmark').onmouseout = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='none';
}
}
//windows.onload=textHints();
//windows.onload=switchToolTip();
//window.onload=init;
document.getElementById("submit-button").onclick = onSubmit;
Your form is getting submitted which results in page reload. That's why you see the message flashing for a while. I saw the commented line in your JavaScript
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
You should get uncomment e.preventDefault().
Grab the click event as function onSubmit(event) and pass the event to checkEmpty.

javascript form validations

I am using javascript validations for required field. Here is my html
<form class="uk-form-stacked" name="myForm" action="<?php echo base_url(); ?>admin/pages/create_service" id="wizard_advanced_form" method="post" enctype="multipart/form-data" onsubmit="return myFunction(this)" novalidate>
<div data-uk-grid-margin="" class="uk-grid">
<div class="uk-width-medium-1-2">
<label for="service_title">Service Title<span class="req">*</span></label>
<input type="text" name="service_title" id="validd" class="md-input" />
<p id="demo"></p>
</div>
</div>
<div class="uk-grid">
<button type="submit" class="md-btn md-btn-primary md-btn-wave-light waves-effect waves-button waves-light" >Submit</button>
</div>
</form>
my javascript is
<script>
function myFunction(form) {
var x, text;
x = document.getElementById("validd").value;
if (x == null || x == "") {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
return false;
}
</script>
Now when my input field is empty and i submit form it shows me input not valid that is fine. but even when i fill some textin input then it shows me undefined in place of input not valid instead of submitting form.
please help..
You forgot to add an else where it would return true if the condition is not satisfied.
<script>
function myFunction(form) {
var x, text;
x = document.getElementById("validd").value;
if (x == null || x == "") {
text = "Input not valid";
document.getElementById("demo").innerHTML = text;
return false;
}
else{
return true;
}
}
</script>
You can use instead:
<html>
<head>
<script>
function valid()
{
var x;
x=document.getElementById(validd).value;
if(x==null || x=="")
{
alert("Please input service title");
document.getElementById(validd).focus();
return false;
}
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return valid()">
<input type="text" name="service_title" id="validd"/>
<button type="submit">Submit</button>
</form>
</body>
</html>`

Categories

Resources