javascript form validation- no popup - javascript

for a uni assignment I need to validate my form before posting it. When an error occurs, there needs to be a text message in the same block as the error-input field (so no pop-up message). I'm not very good at JavaScript so I could really use some help.
Here's my html
<div id="form">
<form name="myForm" method="post" >
<p class="head">Deelnemer</p>
<fieldset id="deelnemer">
<label class="title">Naam:</label>
<input type="text" id="txtName" name="txtName" size="15"/>
</fieldset>
<p class="head">Opmerkingen</p>
<fieldset id="opmerkingen">
<textarea name="opmerkingen" rows="5" cols="40"></textarea>
</fieldset>
<p id="button">
<input type="submit" name="submit" value="Aanmelden" onclick="validate()"/>
</p>
</form>
And my Javascript so far (this show a popup message)
function validate()
{
var userName = document.getElementById("txtName").value;
if (userName.length == 0)
{
alert("Please, enter your name");
return false;
}
else
{
alert("Thank you, " + userName);
}
}
I hope someone has an answer for me! Thanks

So, what you want is just to make appear a message close to the textfield with the error?
For that, you jusst need to modify a little bit your htm and js:
<p class="head">Deelnemer</p>
<fieldset id="deelnemer">
<label class="title">Naam:</label>
<input type="text" id="txtName" name="txtName" size="15"/>
<div id="txtNameError" style="display: none;">Please, enter your name</div>
<p class="head">Opmerkingen</p>
<fieldset id="opmerkingen">
<textarea name="opmerkingen" rows="5" cols="40">
</textarea>
</fieldset>
<p id="button">
<input type="submit" name="submit" value="Aanmelden" onclick="validate()"/>
</p>
</form>
And, in your js file, you replace your alert by the id you need to dispay:
{
var userName = document.getElementById("txtName").value;
if (userName.length == 0)
{
/*alert("Please, enter your name");*/
document.getElementById("txtNameError").style.display = "block";
return false;
}
else
{
alert("Thank you, " + userName);
}
}

Related

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>

How to make a submit button work on a questionnaire

I am making a health questionnaire, I am having a few problems with it. The main problem is the else section. Can someone tell me why it isn't working and help me sort it?
The code I have is:
Assignment 4
Health Questionnaire
<body>
<form name="form1">
Please enter the following details: <p>
First Name: <br>
<input type="text" name="txtFirstName"> size="20" maxlength="20"> <p>
Surname: <br>
<input type="text" name="txtSurName"> size="30" maxlength="20"> <p>
Age: <br>
<input type="text" name="txtAge" size="3" maxlength="3"> <p>
Address Line 1: <br>
<input type="text" name="txtAddressline1" size="30" maxlength="30"> <p>
Address Line 2: <br>
<input type="text" name="txtAddressline2" size="30" maxlength="30"> <p>
City: <br>
<input type="text" name="txtCity" size="20" maxlength="20"> <p>
County: <br>
<input type="text" name="txtCounty" size="20" maxlength="20"> <p>
Post Code: <br>
<input type="text" name="txtPostCode" size="10" maxlength="10"> <p>
<input type="submit" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
<script type ="text/javascript">
function validateForm_onclick()
{
var myForm = document.form1;
if(myForm.txtAge.value === "" || myForm.txtFirstName.value === ""||
myForm.txtSurName.value === ""|| myForm.txtAddressline1.value === ""||
myForm.txtAddressline2.value === ""|| myForm.txtCity.value === ""||
myForm.txtCounty.value === ""|| myForm.txtPostCode.value === "")
{
alert("Please complete all of the form");
if(myForm.txtFirstName.value ==="")
{
myForm.txtFirstName.focus();
}
else
{
myForm.txtSurName.focus();
}
else
{
myForm.txtFirstName.focus();
}
else
{
myForm.txtAge.focus();
}
else
{
myForm.txtAddressline1.focus();
}
else
{
myForm.txtAddressline2.focus();
}
else
{
myForm.txtCity.focus();
}
else
{
myForm.txtCounty.focus();
}
else
{
myForm.txtPostCode.focus();
}
}
else
{
alert("Thanks for completing the form " + myForm.txtName.value);
myForm.submit();
}
}
</script
</form>
</body>
I need to also keep the sizes on the names but need to hide that from the user.
Can someone give me some advice on how to change this?
Your form does not have a submit button.
Your code:
<input type="button" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
Rectified code:
<input type="submit" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
Also, the long list of else is illegal in JavaScript.
form name=form1 needs to have quotes: form name="form1"
And in case you don't want to use submit but stick to a button, insert this in your javascript:
else
{
alert("Thanks for completing the form " + myForm.txtName.value);
myForm.submit();
}

PHP code not working in a Form which is used for javascript

I am working with a form which uses Javascript for a process. When i try to read the textbox value in form with PHP, It's not showing output.
My code is
HTMLCode is
<form class="form-inline" method="POST" action="staff.php" onSubmit=" return questiontable()" >
<div class="form-group">
<label for="qscount">Number of Questions: </label>
<input type="number" name="qscount" class="form-control" id="qscount" style="width:150px;" placeholder="No of questions"> <br>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" id="gobtn" onClick="return disable()" >Go</button> <br>
<p id="btnhide"> </p>
</div>
</form>
Javascript is
<script type="text/javascript">
function questiontable()
{
var qs = document.getElementById("qscount").value;
var count;
for(count=1; count<=qs; count++)
{
document.getElementById("demo").innerHTML += '<br><font style="font-size: 20px">'+ count+'. <input class="textboxtest" style="width:850px;" type="text" name=" q'+ count +' " placeholder="Question "><br>' ;
document.getElementById("demo").innerHTML +='<br><input style="margin-left: 25px;" type="radio" name="a'+count+'" value="c1"> <input class="testbox" type="text" name="o'+count+'1" placeholder="Option 1">';
return false;
}
</script>
PHP Code is
<?php
if (isset($_POST['qscount'])){
echo $_POST['qscount'];
}
?>
I want to use this qscount value in another php page. How to get this textbox value in PHP and use it in another page ?
Javascript function() should return true, since you are using return function() in onclick attribute of button type=submit
<script type="text/javascript">
function questiontable()
{
var qs = document.getElementById("qscount").value;
var count;
for(count=1; count<=qs; count++)
{
document.getElementById("demo").innerHTML += '<br><font style="font-size: 20px">'+ count+'. <input class="textboxtest" style="width:850px;" type="text" name=" q'+ count +' " placeholder="Question "><br>' ;
document.getElementById("demo").innerHTML +='<br><input style="margin-left: 25px;" type="radio" name="a'+count+'" value="c1"> <input class="testbox" type="text" name="o'+count+'1" placeholder="Option 1">';
}
return true;
}
</script>
This will continue the form posting onclick of the button
If you are trying to create the number of questions on click dynamically using javascript,
then use syntax to call questionTable
<button type="button" class="btn btn-primary" id="gobtn" onClick="javascript:return questiontable()" >Create Questions</button>
Remove
onSubmit=" return questiontable()"
from the form
Now when the question table is rendered, please show the button type="submit"
<button type=submit value="Go" name="cmdGo">Go</button>
to trigger form submission
Hope it helps!

Validating form after error has been shown

I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}

Why isn't my instantaneous validation displaying anything?

I have a form that has a number of fields on it. When the user inputs anything, the field should automatically begin sending feedback as to whether or not the input is valid. The javascript code listed is suppose to handle the instantaneous feedback but it gives no reply whatsoever. It is also suppose to stop the form from being submitted if any of the user's input does not match the regular expressions. The regular expressions don't work either but they were working perfectly fine before I used the innerHTML. I would go back to using alerts if using innerHTML wasn't mandatory.
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]{5,40}$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
} else {
return valid;
}
}
function test() {
var result = true;
if (!insert()) {
result = false;
}
return result;
}
This is the html form that the javascript function is referencing.
<form name="Insert" id="I2" action="order.php" method="post" style="display: none;" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off" autofocus>Name <span id="MessNM"></span>
<br>
<input type=email id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type=password id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type=password id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type=text id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type=text id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
There are several issues I see.
You have style="display: none;" on the form which makes the whole form invisible.
Your validation function returns false on the first failed validation which means you're only going to show an error message for the first invalid field, e.g. if e-mail address and zip code are invalid you'll only get a message for e-mail address.
The regular expression for the address validation is broken.
When the password confirmation error is fixed the error message doesn't clear.
By the fact that you say it was working when you used alerts, I'm guessing the main issue you're talking about is caused by the fact that each field validation returns false. You probably just had alerts before and returned a boolean at the end of the function. Here's a solution that addresses that issue and the others I mentioned above.
<form name="Insert" id="I2" action="order.php" method="post" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off"/>Name <span id="MessNM"></span>
<br>
<input type="email" id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type="password" id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type="password" id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type="text" id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type="text" id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]*$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
return valid;
}

Categories

Resources