Check box validation code? - javascript

I am experimenting with a form that has a text field and a check box. I am a designer and not a developer. I have successfully gotten the text box to Validate, but I have pasted in code for the checkbox, which for some reason either cancels out the validation or returns an error at the paypal server. Can anyone suggest a few lines of code to validate the checkbox "terms"? The textbox is called "os0"
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" id="myForm" onSubmit="return validateForm()" >
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="AXNKKDCZLVHM4">
<table width="100%" border="0">
<tr>
<th scope="row"><input type="hidden" name="on0" value="Your RCEH Account Number:" />
Your RCEH Account Number:
</th>
<td>
<input type="text" name="os0" maxlength="200" />
</td>
</tr>
<tr>
<th scope="row"> </th>
<td><label>
<input type="checkbox" name="terms" id="terms" />
Agree to terms and conditions</label>
</td>
</tr>
</table>
<input type=submit value="Proceed to secure server">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
</div>
<script>
function validateForm() {
var x=document.forms["myForm"]["os0"].value;
if (x==null || x==""){
alert("RCEH account number must be filled out");
return false;
}
}
</script>

Assuming that you only want your checkbox to be checked, below there is the code you need, and this is a working JSFiddle.
function validateForm() {
var form = document.getElementById("myForm"); //get the form element via ID
if (form.os0.value == "")
{
alert("RCEH account number must be filled out");
return false;
}
if (!form.terms.checked) { // checks if the checkbox called "terms" is checked; if it is not, alerts a message and return false
alert("Terms must be read and approved");
return false;
}
return true; //if everything is okay, return true and submit the form
}

Related

Javascript Form Validation, multiple functions on a single button not working correctly

I'm working on a form validation project that requires multiple input fields connected to a single submit button. I more or less figured the button out, but I'm having an issue getting the functions themselves to work properly. I currently only have three of the eleven fields typed up for testing, but what the page should do is let you know which fields are invalid when there is nothing filled out in them (changing text/background colors, message below, etc).
The issue I'm having is that when the requirements for the first field (Gift Card Number) are met, it acts as though there isn't any issues anywhere, regardless of whether or not the other input fields (First name, Last name) have been filled. They all seem to function correctly if none of the fields are filled, but my concern is that the functions seem to be firing in order and first one to work negates all the ones after (for example, Gift Card prevents First and Last, First prevents Last, etc).
Any ideas where I've gone wrong here? I'll include my html and my javascript. (Yes, I know the html is a bit ugly, I plan to move the material over to a div table later, just trying to get it to function for now) Any help appreciated as always!
HTML
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<table>
<tbody>
<tr id="rONE">
<td><h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5></td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
</form>
<tr id="rTWO-1">
<td><h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td><form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4></td>
</form>
</tr>
<tr>
<td><h5 id="recipientMessage"></h5></td></td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>
</body>
<footer>
<script src="Form Validation.js"></script>
</footer>
</html>
Javascript
document.getElementById('btn').addEventListener('click', function(){
validateGiftCard();
validateRecipient();
});
function validateGiftCard() {
valid = true;
if ( document.giftForm.giftInput.value == "" )
{
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if ( document.firstForm.firstInput.value == "" )
{
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor="#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
document.getElementById('btn').addEventListener('click', function(e) {
var v1 = validateGiftCard();
var v2 = validateRecipient();
console.log(v1, v2);
if (!v1 || !v2)
e.preventDefault();
});
function validateGiftCard() {
valid = true;
if (document.giftForm.giftInput.value == "") {
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if (document.firstForm.firstInput.value == "") {
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor = "#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
<table>
<tbody>
<tr id="rONE">
<td>
<h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5>
</form>
</td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
<tr id="rTWO-1">
<td>
<h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td>
<form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4>
</form>
</td>
</tr>
<tr>
<td>
<h5 id="recipientMessage"></h5>
</td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>

Javascript form validation doesn't return anything

I have an HTML form with some fields and a javascript validation that checks them, my problem is that js doesn't return anything, and although the fields are filled not propertly the submit sends.
Here an example of my code:
HTML
<form method="post" action="action.php" onsubmit="return validate_form();">
<table>
<tr>
<td>
<label class="standard_text">
E-mail
</label>
</td>
<td><input class="textarea" required type="email" name="mail" id="mail" placeholder="E-mail"></label></td>
<td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
<td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
<td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
</tr>
</table>
<input class="button_submit" type="submit" name="send_form" value="Register"/>
</form>
Javascript
function validate_form(){
//email var
var mail = document.getElementById("mail").value;
var mail_ok_icon = document.getElementById("mail_ok_icon");
var mail_no_icon = document.getElementById("mail_no_icon");
var mail_message = document.getElementById("mail_message");
//email format check
if ((/(.+)#(.+){2,}\.(.+){2,}/.test(mail)) || mail=="" || mail==null) {
mail_no_icon.style.display="block";
mail_message.style.display="block";
return(false);
} else {
mail_ok_icon.style.display="block";
}
}
So I'm trying to display elements depending on the javascript checking and also trying to don't let the user send the information if the checking of all the fields are not correct.
What am I missing?
Thanks
I got it working with the following code -:
In the original code the email input had required and type="email" which never called the javascript code in the first instance.
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form method="post" action="action.php" onsubmit="return validate_form();">
<table>
<tr>
<td>
<label class="standard_text">
E-mail
</label>
</td>
<td><input class="textarea" name="mail" id="mail" placeholder="E-mail"></label></td>
<td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
<td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
<td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
</tr>
</table>
<input class="button_submit" type="submit" name="send_form" value="Register"/>
</form>
</body>
</html>
Now here is the js code -:
function validate_form() {
//email var
var mail = document.getElementById("mail").value;
var mail_ok_icon = document.getElementById("mail_ok_icon");
var mail_no_icon = document.getElementById("mail_no_icon");
var mail_message = document.getElementById("mail_message");
//email format check
if (!(/(.+)#(.+){2,}\.(.+){2,}/.test(mail)) || mail=="" || mail==null) {
mail_no_icon.style.display="block";
mail_message.style.display="block";
console.log('hi');
return false;
} else {
mail_ok_icon.style.display="block";
return true;
}
}

Javascript function does not display alert box

I have a javascript project I am working on that take information and submits it. I am supposed to validate that the quantity inputs only have numbers in them and pop up an alert box and not submit if they do not. They can be blank as long as if they have anything input it is only numbers. I have validated it, and looked at the submission page and it shows that if I put in letters the particular quantity field does not submit (I have three quantities), but everything else does. It is supposed to throw up an alert and stop the page from submitting if any of the quantities are not numbers. I have looked at this over and over and tried a few things, but cannot seem to find my error. I would appreciate any direction on where to look to correct this.
<script>
//function to check for valid fruit quantities
function certifyDigits() {
var b = document.getElementById("blueberries").value;
var c = document.getElementById("cherries").value;
var s = document.getElementbyId("strawberries").value;
if (!b.match(/^\d+$/)) {
alert("Please enter only numbers for quantity!");
return false;
}
if (!c.match(/^\d+$/)) {
alert("Please enter only numbers for quantity!");
return false;
}
if (!s.match(/^\d+$/)) {
alert("Please enter only numbers for quantity!");
return false;
}
}
</script>
</head>
<body>
<h2>Fruit Purchasing Form</h2>
<table class="main">
<tr>
<th class="a"> </th>
<th class="a">Blueberries</th>
<th class="a">Cherries</th>
<th class="a">Strawberries</th>
</tr>
<tr>
<th class="a">Price</th>
<td class="b">$2.50</td>
<td class="b">$4.40</td>
<td class="b">$8.00</td>
</tr>
<tr>
<th class="a">Shipping Weight</th>
<td class="b">2.0</td>
<td class="b">4.0</td>
<td class="b">4.0</td>
</tr>
</table>
<br />
<br />
<br />
<br />
<form name="fruitOrder" action="http://www.textXXX.php" method="post" onSubmit="return certifyDigits()">
<h3>Select Quantity of Fruit Desired</h3>
<br />
<p>Blueberries:</p>
<input id="blueberries" type="text" size=5>
<p>Cherries:</p>
<input id="cherries" type="text" size=5>
<p>Strawberries:</p>
<input id="strawberries" type="text" size=5>
<br />
<br />
<h3>Customer Information</h3>
<br />
<label>Your Last Name:
<input type="text" name="lastname" id="lastname" size="25" />
</label>
<br />
<label>Your First Name:
<input type="text" name="firstname" id="firstname" size="25" />
</label>
<br />
<label>Street Address:
<input type="text" name="street" id="street" size="60" />
</label>
<br />
<label>City, State, Zip Code:
<input type="text" name="citystatezip" id="citystatezip" size="60" />
</label>
<br />
<h3>Payment Method</h3>
<label>Visa
<input type="radio" name="payment_type" id="payment_type_Visa" value="Visa" checked />
</label>
<br />
<label>Mastercard
<input type="radio" name="payment_type" id="payment_type_MC" value="MC" />
</label>
<br />
<label>American_Express
<input type="radio" name="payment_type" id="payment_type_amex" value="amex" />
</label>
<br />
<br />
<input type="submit" value="SUBMIT" />
</form>
The javascript match() function always returns an array. If the match is true, then the array will contain the matching value. If the match is false, then the array will contain an empty string. Change your if statements to
if (b.match(/^\d+$/)[0] === "") {
That should fix it.
Why not validate the input for numbers only?
function validate_numbers(evt){
var theEvent=evt || window.event;
var key=theEvent.keyCode || theEvent.which;
key=String.fromCharCode(key);
var regex=/[0-9]|\.|\,|\/|\ /;
if(!regex.test(key)){
theEvent.returnValue=false;
if(theEvent.preventDefault)theEvent.preventDefault();
};
};
It should be: document.getElementById("strawberries").value;
Not: document.getElementbyId("strawberries").value;
You are using small letter b for getElementById which causes an error.
To easily see errors like this, enable preserve log on chrome. On my end the error is: Uncaught TypeError: document.getElementbyId is not a function
To prevent the page from sending on error add return false; in function certifyDigits(). You can also set variables that will store number of errors, if there is an error, return false.
See below.
function certifyDigits(){
var fruits = ["blueberries", "cherries", "strawberries"];
var errors_count = 0;
for(var ctr = 0; ctr < fruits.length; ctr ++){
if(! document.getElementById(fruits[ctr]).value.match(/^\d+$/)){
errors_count++;
}
}
if(errors_count > 0){
alert("Please enter only numbers for quantity!");
return false;
}
}
By the context, you were using match instead of test.
To make everything works correctly, use /^\d+$/.test(b) this will return True or False, and you may want to alert once if either of them input is incorrect (instead of three alerts), to do this include || in the if statement which stands for or, Cheers !

Javascript confirm box

i try to use confirm box but it does not work after 'OK' pressing
this is my confirm box
<script language="JavaScript">
{literal}
function confirmBox()
{
var where_to= confirm("Silmek istediğinizden emin misiniz?");
if (where_to== true)
return true;
else{
alert("Silme işleminden vazgeçtiniz yönlendiriliyorsunuz");
return false;
}
}
{/literal}
</script>
<form name="removeFortune" method="post" action="#">
<table border="0" name="tableArticle">
{foreach from=$articles value=article}
<tr>
<td><input type="checkbox" name="checkArticle[]" value="{$article.id}" /></td>
<td>{$article.title}</td>
</tr>
{/foreach}
</table>
<input type="submit" onclick="confirmBox()" name="removeArticle" value="Sil" />
<br /><br />
{$deleteMessage}
</form>
If you want it to submit after pressing OK, you need to change 1 simple thing. Add a return
onclick="return confirmBox()"
Although I would say:
onsubmit="return confirmBox()"

Enter key hook with html form

I implemented form in HTML:
<form id="loginForm" action="/?do=login" method="post" >
<table width="50%" border="0">
<tr>
<td colspan="2">
<span id="LoginErr"></span>
<div>Login:</div>
<input id="Login" type="text" maxlength="32" name="Login" value="{VAR %LOGIN}"/>
</td>
</tr>
<tr>
<td valign="bottom">
<span id="PasswordErr"></span>
<div>Passoword:</small></div>
<input id="Password" type="password" maxlength="128" name="Password" value=""/>
</td>
</tr>
<tr>
<td>
Enter
</td>
</tr>
</table>
</form>
This is the check and post function (using jQuery):
function checkLogin()
{
var focused = false;
function report_error(field, err)
{
$('#' + field + 'Err').html(err);
if (!focused)
{
$('#' + field).focus();
focused = true;
}
}
$('#LoginErr').html('');
$('#PasswordErr').html('');
$login = jQuery.trim($('#Login').val());
$password = jQuery.trim($('#Password').val());
if ($login.length == 0)
report_error('Login', 'The login field is empty!');
if ($password.length == 0)
report_error('Password', 'The password field is empty!');
if (!focused)
$('#loginForm').submit();
}
But I have trouble with enter key. When i press this key form is posted without my javascript check.
I need call my function when enter key is pressed and no more action.
Thanx!
Update:
Correct code is:
in form tag need add: onSubmit="return checkLogin()
in javascript if (!focused) $('#loginForm').submit(); need change on return !focused;
Thanks to rdamborsky.
use onSubmit form event:
$(function() {
$('#loginForm').onSubmit = checkLogin;
});
It will be called just before your form's data are actually sent whatever triggers the submit event (click on button, pressing enter within one of fields...)

Categories