inline javascript form validation - javascript

I'm working on a form validation script at work and am having some difficulty. The form is meant to make sure that the user fills out a name, a real-looking email, a category (fromt he drop down) and a question:
This names the form and gathers all the data up from the form:
<script>
function checkForm(form1) {
name = document.getElementById("FieldData0").value;
category = document.getElementById("FieldData3").value;
question = document.getElementById("FieldData1").value;
email = document.getElementById("FieldData2").value;
This checks to see that something is in the "name" field. It works fine and validates exactly like it should, displaying the error text:
if (name == "") {
hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("FieldData0").select();
document.getElementById("FieldData0").focus();
return false;
This also works just like it should. It checks to see if the email field is empty and if it is empty,displays error text and selects that field:
} else if (email == "") {
hideAllErrors();
document.getElementById("emailError").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
This also works just like it should, makes sure that the questions field isn't empty:
else if (question == "") {
hideAllErrors();
document.getElementById("questionError").style.display = "inline";
document.getElementById("FieldData1").select();
document.getElementById("FieldData1").focus();
return false;
}
This one works partially - If no drop down is selected, it will display the error message, but that doesn't stop the form from submitting, it just displays the error text while the form submits:
else if (category == "") {
hideAllErrors();
document.getElementById("categoryError").style.display = "inline";
document.getElementById("FieldData3").select();
document.getElementById("FieldData3").focus();
return false;
}
This one doesn't work at all no matter where I put it. I used a variation on the same script last week and it worked fine. This is supposed to check to see that the email entered looks like a real email address:
else if (!check_email(document.getElementById("FieldData1").value)) {
hideAllErrors();
document.getElementById("emailError2").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
Otherwise it lets the form submit:
return true;
}
This checks the email out:
function check_email(e) {
ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i=0; i < e.length ;i++){
if(ok.indexOf(e.charAt(i))<0){
return (false);
}
}
if (document.images) {
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!e.match(re) && e.match(re_two)) {
return (-1);
}
}
}
This function hides all errors so the user isn't bombarded with red text. I tried putting in "document.getElementById("emailError").style.display = "none"" but that breaks the whole thing:
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
</script>
And the form looks like this:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<p><div class=error id=nameError>Required: Please enter your name<br/></div><p><strong>Name:</strong> <span></span><br><input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
<label for="name"></label></p>
<p><div class=error id=emailError>Required: Please enter your email address<br/></div>
<div class=error id=nameError2>This doesn't look like a real email address, please check and reenter<br/></div>
<strong><p>Email:</strong> <span>(will not be published)</span><br><input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
<label for="email"></label>
</p>
<div class=error id=categoryError>Please select a category from the drop-down menu<br></div>
<p><strong>Category:</strong> <span></span><br>
<p><select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select><label for="category"></label>
<p><div class=error id=questionError>Please type your question in the box below:<br></div><label for="question"><strong><p>Your Question:</strong> <span></span></label><br>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea></p>
<p><input type="submit" class="btn" value="Submit Question" name="Submit"></p>
</div>
</form>
Is the problem the order that I run the checks? I can't seem to figure this out. Any help would be appreciated.

I've taken the liberty to re-write your javascript to make it more readable and easier to debug.
As Marc Bernier mentioned, the dropdown element does not support the select function so I put an if statement around it to prevent an exception. I've also simplified your checkEmail function, it seemed rather convoluted. I renamed it to isAnInvalidEmail in order to make the checkForm code simpler.
You have also incorrectly named the 'emailError2' div in your HTML, which would cause another exception in the javascript. Your HTML is rather messy and, in some cases, invalid. There are missing quotes on some attribute values and missing end-tags. You should consider using the W3C validator to ensure your HTML is clean and is standards compliant.
I've hosted your code on jsbin: http://jsbin.com/iyeco (editable via http://jsbin.com/iyeco/edit)
Here's the cleaned up Javascript:
function checkForm() {
hideAllErrors();
var formIsValid =
showErrorAndFocusIf('FieldData0', isEmpty, 'nameError')
&& showErrorAndFocusIf('FieldData2', isEmpty, 'emailError')
&& showErrorAndFocusIf('FieldData2', isAnInvalidEmail, 'emailError2')
&& showErrorAndFocusIf('FieldData3', isEmpty, 'categoryError')
&& showErrorAndFocusIf('FieldData1', isEmpty, 'questionError');
/* For debugging, lets prevent the form from submitting. */
if (formIsValid) {
alert("Valid form!");
return false;
}
return formIsValid;
}
function showErrorAndFocusIf(fieldId, predicate, errorId) {
var field = document.getElementById(fieldId);
if (predicate(field)) {
document.getElementById(errorId).style.display = 'inline';
if (field.select) {
field.select();
}
field.focus();
return false;
}
return true;
}
function isEmpty(field) {
return field.value == '';
}
function isAnInvalidEmail(field) {
var email = field.value;
var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i = 0; i < email.length; i++){
if(ok.indexOf(email.charAt(i)) < 0) {
return true;
}
}
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return re.test(email) || !re_two.test(email);
}
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("emailError2").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
And the cleaned up HTML:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<div>
<div class="error" id="nameError">
Required: Please enter your name
</div>
<label for="FieldData0"><strong>Name:</strong></label>
<input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
</div>
<div>
<div class="error" id="emailError">
Required: Please enter your email address
</div>
<div class="error" id="emailError2">
This doesn't look like a real email address, please check and reenter
</div>
<label for="FieldData2"><strong>Email:</strong>(will not be published)</label>
<input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
</div>
<div>
<div class="error" id="categoryError">
Please select a category from the drop-down menu
</div>
<label for="FieldData3"><strong>Category:</strong></label>
<select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select>
</div>
<div>
<div class="error" id="questionError">
Please type your question in the box below:
</div>
<label for="FieldData1"><strong>Your Question:</strong></label>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea>
</div>
<input type="submit" class="btn" value="Submit Question" name="Submit">
</form>

Regarding the error on the drop-down, don't call this line:
document.getElementById("FieldData1").select();
I seem to recall having the exact same problem a few weeks ago.

First problem: move the content of that if statement into a function...then go from there. You have about 5 pieces of code doing essentially the same thing.
Next: since you're only allowing one error message at a time, create a generic div to hold it and just move the thing. That way, you don't need to keep track of hiding certain errors, displaying others, etc.
Next: only return true or false from your check_email function...returning -1 and false, etc. is bad form even though javascript is lenient on such things.
After you have cleaned up your code, it will be much easier to debug.

I would recommend getting rid of the whole if else chain and check each on individually this this.
var error = 0;
if (value == '') {
error = 1;
// other stuff;
}
if (value2 == '') {
error = 1;
// do stuff;
}
...
if (error) {
// show error
} else {
// submit form
}

Try replacing the == for === which doesn't type cast. It might help you with the dropdown problem.
Your function is returning false and it might also return -1.
As I don't know what type cast JavaScript does with !-1 you should also do this:
check_email(...)!==false;
Instead of this:
!check_email(...)

Related

Validate a form with multiple elements?

I have a form that has multiple elements/types
inputs for name, email, address, etc.
radio button for shipping speed.
select tags for "state" & "credit card type".
I want to disable the submit button until the:
1.inputs are filled out.
the select tags have an option selected
the radio is checked.
I've selected the elements (see below);
const btn = document.querySelector('#olegnax-osc-place-order-button');
let inputs = document.querySelectorAll('#olegnax-osc-billing-address-list .required-entry, input#authorizenet_cc_number');
let selectTags = document.querySelectorAll('#olegnax-osc-billing-address-list select, #payment_form_authorizenet select');
let radio = document.querySelector('#s_method_owebiashipping1_id_06');
My question is, being the form consists of 3 different types (input, select, radio), can I just create one array with all of these elements and loop though to make sure the value for each is not blank?
For example, say I store all the different elements in an array called "requiredFields" would this work?:
for (var i = 0; i < requiredFeilds.length; i++) {
if (requiredFeilds[i].value === '') {
btn.disabled = true;
}else {
btn.disabled = false;
}
}
There's a lot more to form validation than meets the eye, but that being said you have a major flaw in your logic. Namely, as you loop over all the fields, you could be changing btn.disabled back and forth depending on the value of the form field (or lack of a value).
Instead, begin with the button disabled, and then instead of looping, use Array.prototype.some (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) to check if any field is missing a value, something such as:
btn.disabled = requiredFields.some(field => field === '');
There's lots else to address with regards to your approach but this corrects your current logic error and is much more concise.
You can loop through everything but the radio buttons easily. For the radio buttons, you want to check if any of the buttons in a radio group are checked, so it is a little more complicated. It might be easier to just designate a radio button as default, with the checked attribute:
document.querySelector("input[type=submit]").disabled = true;
const inputs = Array.prototype.slice.call(document.forms["form1"].querySelectorAll("input[type=text], select"));
document.forms["form1"].addEventListener("input", () => {
let complete = true;
inputs.forEach((field) => {
if(field.value.trim() === "") {
complete = false;
}
});
document.querySelector("input[type=submit]").disabled = !complete;
});
form{
display:flex;
flex-flow:column;
align-items:flex-start;
}
<form name="form1" id="form1">
<input type="text" name="bar" />
<input type="text" name="foo" />
<select name="biz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<select name="baz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<label>
A <input type="radio" name="buzz" value="a" checked />
</label>
<label>
B <input type="radio" name="buzz" value="b" />
</label>
<input type="submit" value="Submit" />
</form>
Yes, just combine your selectors and use a comma, and check tagName:
const requiredFields = document.querySelectorAll( "
#olegnax-osc-place-order-button,
#olegnax-osc-billing-address-list .required-entry,
input#authorizenet_cc_number,
#olegnax-osc-billing-address-list select,
#payment_form_authorizenet select,
#s_method_owebiashipping1_id_06
" );
for( let input of requiredFields ) {
if( input.tagName == "INPUT" ) {
}
else if( input.tagName == "SELECT" ) {
}
else if( input.tagName == "TEXTAREA" ) {
}
}
You should also use the required attribute too:
<input type="text" required />
<select required></select>
<textarea required></textarea>

Validating a form when either a "select" OR "input" is required

I have a page containing multiple forms, all different, and when one is submitted I use the function below to gather all the inputs from that form with the class "required" and check for empty values:
function validateForm(form) {
var inputs = form.getElementsByTagName('input');
var selects = form.getElementsByTagName('select');
var errors = 0;
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].classList.contains('required')) {
if(inputs[i].value === "") {
inputs[i].classList.add("warning");
errors++;
} else {
inputs[i].classList.remove("warning");
}
}
}
if(errors) {
return false;
} else {
return true;
}
}
If it finds an empty value, it adds the class "warning" which just gives the input a red border, then returns false so the form doesn't get submitted.
Here's where I'm running into trouble: Some forms contain a <select> and a text input, ONE of which must be filled in, but not both, as well as various other text inputs. I'm trying to figure out how to modify the above function to handle this.
Let's say the form is for adding a new product. The select is dynamically populated with existing product "categories" and the text input is for if the user wants to create a new category. Here's a simplified version of the form:
<form method = "post" onsubmit = "return validateForm(this)">
<div class = "form-group">
<label>Product Name</label>
<input class = "form-control required" type = "text" name = "product" />
</div>
<div class = "form-group">
<select class = "form-control required" id = "category" name = "category[]">
<option value = "">Select Existing Category</option>
<option value = "Shirts">Shirts</option>
<option value = "Shoes">Shoes</option>
<option value = "Pants">Pants</option>
</select>
</div>
<div class = "form-group">
<label>Create New Category</label>
<input class = "form-control required" type = "text" name = "category[]" />
</div>
<div class = "form-group">
<input class = "btn btn-primary" type = "submit" value = "Submit" />
</div>
</form>
Since I'm using a for loop to go through the inputs - the select and the input are not going to have the same index, so I can't do something like this:
if((selects[i].value === "" && inputs[i].value === "") || (selects[i].value !== "" && inputs[i].value !== "")) {
// add the warning class to both
}
I feel the answer lies somewhere in using the name attribute, i.e. compare selects.name and inputs.name, but how do I get around the differing index in the loop? And also, it should only make this comparison when the select is encountered anyway. It doesn't necessarily exist, depending on the form.
Basically, I need to modify my function to do this:
I. Gather all inputs and selects (if any - some forms will not) from a submitted form
II. Make sure none of the inputs with the "required" class are blank (unless there's a corresponding select, in which case see III below)
III. If there's a select, find the text input with the same "name" (not a requirement to have the same name, but I assume this is the right way to do it). One of them, but not both, must have a value. If both are blank, or both have a value, they should get the "warning" class;
Any help anyone can offer will be greatly appreciated!
Here's a function that do exactly what you want and can handle any form you want, as long as they have the same HTML structure.
Notes:
I recommend avoiding inline event listeners as much as you can, in
the snippet below I used addEventListener method to attach submit
event to all the forms in the document, you can change this to just
some specific forms if you want.
Instead of only adding a border to the required elements, I suggest
you also add some text to tell what the problem is.
// getting all forms in the page you can also get specific forms based on their class-name
var forms = document.getElementsByTagName('form'),
l = forms.length,
i = 0;
// adding submit submit event listener to the referenced forms
for(; i < l; i++) {
forms[i].addEventListener('submit', validateForm);
}
function validateForm(e) {
var els = this.querySelectorAll('input.required'),
len = els.length,
err = false,
c = 0,
inpName = '';
// checking if the form has a select, if so, allow only the select or the input to be filled
var isSelect = this.getElementsByTagName('select');
if(isSelect[0] !== undefined && isSelect[0] !== null) {
var inp = isSelect[0].parentNode.nextElementSibling.querySelector('input.required');
inpName = inp.name;
if((isSelect[0].value == '' && inp.value.trim().length === 0) || (isSelect[0].value != '' && inp.value.trim().length > 0)) {
err = true;
isSelect[0].classList.add("warning");
inp.classList.add("warning");
} else {
isSelect[0].classList.remove("warning");
inp.classList.remove("warning");
}
}
// iterate through the rest of the inputs and check for empty one, thus trimming them before checking
for(; c < len; c++) {
if(els[c].name !== inpName) {
if(els[c].value.trim() == '') {
err = true;
els[c].classList.add("warning");
} else {
els[c].classList.remove("warning");
}
}
}
// based on the error variable, either submit the form or cancel submission
(!err) ? this.submit():e.preventDefault();
}
.warning {
border: 2px solid red;
}
<form method="post">
<div class="form-group">
<label>Product Name</label>
<input class="form-control required" type="text" name="product" />
</div>
<div class="form-group">
<select class="form-control required" id="category" name="category[]">
<option value="">Select Existing Category</option>
<option value="Shirts">Shirts</option>
<option value="Shoes">Shoes</option>
<option value="Pants">Pants</option>
</select>
</div>
<div class="form-group">
<label>Create New Category</label>
<input class="form-control required" type="text" name="category[]" />
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="Submit" />
</div>
</form>
Hope I pushed you further.
You may get a message saying: "The custom error module does not
recognize this error." when you successfully submit the form from the
snippet above, that due to StackOverflow's restrictions as they
don't allow/server side code (StackOverflow doesn't let the form to
be submitted).

When editing code that is working on my production site, and testing on the developer site the exact same code will not run

To start, I am a beginner that has started working with my employer on their website. Adding small functions and features here and there. The issue I am coming across is, I am trying to add a reCaptcha to one of our payment pages and when I test the code taken directly from the production site in the developer environment there are features that no longer work. There are radio buttons that drop down when selecting a payment option for credit or debit to add the additional payment information that no longer works when on the developer site. This is the page I am working on: here This is all before even adding the CAPTCHA. That part I did not have a problem with, it is matching the current functionality. I need it to work on the dev site before pushing changes to production. My company currently uses Interchange web-based application server. Here is some of the code:
$(document).ready(function(){
//payment type check
var payType = $('input[name=paymentType]:checked', '#paymentForm').val();
if( payType == null )
{
alert('You have not selected a Payment Type')
return false;
}
//credit card check
if( payType == 'credit' ){
if(IsEmpty(form.cc_type))
{
alert('You have not entered a Credit Card Type')
form.cc_type.focus();
return false;
}
if(IsEmpty(form.ccnum))
{
alert('You have not entered a Credit Card Number')
form.ccnum.focus();
return false;
}
if(IsEmpty(form.ccmo))
{
alert('You have not entered a Credit Card Expiration Month')
form.ccmo.focus();
return false;
}
if(IsEmpty(form.ccyr))
{
alert('You have not entered a Credit Card Expiration Year')
form.ccyr.focus();
return false;
}
if(IsEmpty(form.cvv2_number))
{
// alert('You have not entered the Credit Card CVV2')
// form.cvv2_number.focus();
// return false;
}
}
//checking account check
if( payType == 'check' ){
var chkType = $('input[name=checkingType]:checked', '#paymentForm').val();
if( chkType == null )
{
alert('You have not selected a Checking Type')
return false;
}
if( !form.aba.value.match(/^\d{9}$/) )
{
alert('Checking Routing Number must be 9 digits')
form.aba.focus();
return false;
}
else{
var n=form.aba.value.split('');
var chkSum = ( 3 * (parseInt(n[0]) + parseInt(n[3]) + parseInt(n[6])) +
7 * (parseInt(n[1]) + parseInt(n[4]) + parseInt(n[7])) +
(parseInt(n[2]) + parseInt(n[5]) + parseInt(n[8]))) % 10;
if( chkSum != 0 ){
alert('Checking Routing Number is invalid')
form.aba.focus();
return false;
}
}
if(IsEmpty(form.account))
{
alert('You have not entered a Checking Account Number')
form.account.focus();
return false;
}
}
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
var submitted = false;
$(document).ready(function(){
try {
$('#item_1_cost').priceFormat({
prefix: '',
thousandsSeparator: ''
});
} catch (e) { console.log(e); }
$('#item_1_cost').val('[scratch form-item_1_cost]');
$('.trimMe').focusout(function(){
$(this).val( $.trim($(this).val()) );
});
var updateBilling = function () {
if (!$("#sameAsShipping").is(":checked")) { return }
$("#address").val( $("#saddr").val() );
$("#city").val( $("#scity").val() );
$("#state").val( $("#sstate").val() );
$("#zip").val( $("#szip").val() );
}
$('.paymentTypeRadio').change(function(){
$('#paymentCredit').hide();
$('#paymentCheck').hide();
var payType = $('input[name=paymentType]:checked', '#paymentForm').val();
if(payType == "credit") {
$('#pass_action').val('iTransact');
document.paymentForm.action = "https://secure.paymentclearing.com/cgi-bin/rc/ord.cgi";
$('#paymentCredit').show();
$('#aba').val('');
$('#account').val('');
$('#account_source').val('');
} else if( payType == "check" ){
$('#pass_action').val('##MV_PAGE##');
document.paymentForm.action = "https://__SERVER_NAME__/##MV_PAGE##.html";
$('#paymentCheck').show();
$('#ccnum').val('');
$('#ccmo').val('');
$('#ccyr').val('');
$('#cvv2_number').val('');
}
});
$('.patientGroup').keyup(function(){ updateBilling() });
$('.patientGroup').change(function(){ updateBilling() });
$("#sstate").val("[scratch form-sstate]");
$("#state").val("[scratch form-state]");
// Add onclick handler to checkbox w/id checkme
$("#sameAsShipping").click(function(){
// If checked
if ($("#sameAsShipping").is(":checked")) {
$(".billingGroup").attr("readonly", true);
$("#first_name").val( $("#sfname").val() );
$("#last_name").val( $("#slname").val() );
updateBilling();
} else {
$(".billingGroup").val('');
$("#first_name").val('');
$("#last_name").val('');
$(".billingGroup").removeAttr("readonly");
}
});
}); // document ready
var pop_window;
function popWin(pop_url) {
pop_window = open(pop_url, 'package_info',',width=500,height=450,scrollbars=yes,resizable=yes');
}
function IsEmpty(aTextField) {
if ((aTextField.value.length==0) || (aTextField.value==null)) return true;
return false; // no need for else as if the statment is true this line will not run anyway
}
function ValidateForm(form) {
if( submitted == true ) {
alert("You have already submitted. Please wait while the page processes. Thank you.");
return false;
}
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<div class="mybinsonsform" style="width: 680px;">
<input type="text" name="ccnum" id="ccnum" class="trimMe" VALUE="" size="30" maxlength="20">
</div>
<div class="mybinsonsform" style="width: 680px;">
<select name="ccmo" id="ccmo">
<option value="">Month</option>
<option value="January">01 January</option>
<option value="February">02 February</option>
<option value="March">03 March</option>
<option value="April">04 April</option>
<option value="May">05 May</option>
<option value="June">06 June</option>
<option value="July">07 July</option>
<option value="August">08 August</option>
<option value="September">09 September</option>
<option value="October">10 October</option>
<option value="November">11 November</option>
<option value="December">12 December</option>
</select>
<select name="ccyr" id="ccyr" style="width:70px;">
<option value="">Year</option>
</select>
</div>
<div class="mybinsonsform" style="width: 680px;">
<input type="text" name="cvv2_number" id="cvv2_number" class="trimMe" value="" size="5" maxlength="5">
<a href="[area href=special/cvv_pop]" target="package_info" onclick="popWin('[area href=special/cvv_pop]'); return false;">
<small>Where is it?</small>
</a>
</div>
<!-- Checking information -->
<div id="paymentCheck" style="display:none;">
<div class="mybinsonsform" style="width: 680px;">
<input type="radio" class="checkingTypeRadio" name="checkingType" value="acctChecking"> Checking Account
<input type="radio" class="checkingTypeRadio" name="checkingType" value="acctSavings"> Savings Account
</div>
<div class="mybinsonsform" style="width: 680px;">
<input type="text" name="aba" id="aba" class="trimMe" VALUE="" size="10">
</div>
<div class="mybinsonsform" style="width: 680px;">
<input type="text" name="account" id="account" class="trimMe" VALUE="" size="10">
</div>
</div>
If there is any more information I can provide please let me know. I appreciate any assistance! Thank you in advance!
-Tim
Are you sure that JQuery is being loaded? The piece of code responsible for showing/hiding the payment type fields is this:
$('.paymentTypeRadio').change(function() {
$('#paymentCredit').hide();
$('#paymentCheck').hide();
var payType = $('input[name=paymentType]:checked', '#paymentForm').val();
if (payType == "credit") {
$('#pass_action').val('iTransact');
document.paymentForm.action = "https://secure.paymentclearing.com/cgi-bin/rc/ord.cgi";
$('#paymentCredit').show();
$('#aba').val('');
$('#account').val('');
$('#account_source').val('');
} else if (payType == "check") {
$('#pass_action').val('payment');
document.paymentForm.action = "https://www.binsons.com/payment.html";
$('#paymentCheck').show();
$('#ccnum').val('');
$('#ccmo').val('');
$('#ccyr').val('');
$('#cvv2_number').val('');
}
});
It's using JQuery so perhaps it's not being loaded locally. Look for 404 errors in your console, or errors along the lines of $ is not a function.

Need with Javascript function for Select check

I tried to create a function to check on a drop-down option on select box. It requires a user to select a user name before submit. I put '0' and check if this = 0, then return false, but it didn't work.
I added a function to check radio buttons and they all worked fine. However, the select Staff doesn't work. I mean, when I click on Submit after checking all radio boxes, it get submitted anyway. How do I fix it to make it work?
Can you help me?
<script language="javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
// check all rb radio buttons
for (var i = 1; i < nCount; i++) {
if (! getCheckedRadioValue(daForm["Report"+i])) {
alert ("Please select a value for option " + i)
return false
}
if (UserID.options[UserID.selectedIndex].value == 0) {
alert("Please select a user");
return false
}
// add other checks here...
alert ("Thank you!")
window.open("Search.asp")
return true
}
<body>
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
<select name="UserID">
<option value=0>Staff name:</option>
<option value=1>Jenny</option>
<option value=2>David</option>
</select>
<input type="submit" value="Submit">
</form>
Thank you very much!
It looks like something is wrong with the selector.
Comparing against a "0" value seems to work just fine. I've included a snippet which shows this.
In short, change this...
if (UserID.options[UserID.selectedIndex].value == 0) {
alert("Please select a staff");
return false
}
To this
if (document.querySelector("[name='UserID']").value == 0) {
alert("Please select a staff");
return false
}
Make multiple selections and submit to see the results.
function validateForm(daForm){
var select = document.querySelector("[name='UserID']")
if(select.value == 0){
console.log("Please select a value");
}else{
console.log("Selection made.");
}
return false;
}
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
<select name="UserID">
<option value=0>Staff name:</option>
<option value=1>Jenny</option>
<option value=2>David</option>
</select>
<input type="submit">
</form>
You cannot just use UserID and work on it with JavaScript. That is the name of the select element. What you need to do is to select it using JavaScript and then work with it.
var UserID = document.getElementsByName("UserID")[0];
if (UserID.options[UserID.selectedIndex].value == 0) {
alert("Please select a staff");
return false
}
// add other checks here...
alert ("Thank you!")
return true;
}
<== Fiddle Me ==>

Html and javascript box authentication

In the following code I am trying to get the select box to display a message beside the box if it hasn't selected a value of male or female. and not show it if it has one of these values selected. but it isnt working, it works fine with the text boses for email and password can anyone see why this isnt working and help me with the answer.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!-- saved from url=(0045)https://vle.wit.ie/file.php/8220/lab5pt2.html -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function validate_gender(field,alerttxt)
{
with (field){
apos=value.indexOf("0");
if (apos>0)
{
document.getElementById('gender_help').innerHTML="";
return true;
}else{
document.getElementById('gender_help').innerHTML=alerttxt;
return false;
}
}
}
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("#");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{document.getElementById('email_help').innerHTML=alerttxt;return false; }
else {document.getElementById('email_help').innerHTML="";return true;}
}
}
function validate_password(field, alerttxt){
with (field){
var re = /^[a-zA-Z0-9]{6,8}$/;
if (re.test(value))
{
document.getElementById('pass_help').innerHTML="";
return true;
}else{
document.getElementById('pass_help').innerHTML=alerttxt;
return false;
}
}
}
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (!validate_gender(gender,"A Valid gender is Required"))
{gender.focus();return false;}
if (!validate_email(email,"A Valid Email is Required"))
{email.focus();return false;}
if (!validate_password(pass,"Password must be between 6 and 8 characters and contain both numbers and alphas"))
{pass.focus();return false;}
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validate_form(this)" method="post">
What is your gender?<br />
<select name="gender" ><span id="gender_help"></span>
<option value="0" selected="selected">Select...</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select><br/>
Email: <input type="text" name="email" size="30" ><span id="email_help"></span><br>
Password <input type="password" name="pass" size="30"><span id="pass_help"></span><br>
<input type="submit" value="Submit">
</form>
</body></html>
This is a shocking display of anti-patterns!!
Don't use with.
Cache your selectors i.e. var emailHelper = document.getElementById('email_help')
Don't use inline javascript i.e onClick=''
Consider using a library like jQuery to handle events in a cross-browser way.
Generally it's not good to put braces on a new line.
You shouldn't have a <span> inside of the <select> element.
Check out http://javascript.crockford.com/ or http://eloquentjavascript.net/ for some other tips and tricks and best practices. Also more about why not to use with here: Are there legitimate uses for JavaScript's "with" statement?
Now on to the actual question!
You're having trouble with the select box. Let's try something like this:
var genderHelper = document.getElementById('gender_help')
function validate_form(thisform) {
// your other stuff
if (!validate_gender(thisform.gender.value,"A Valid gender is Required")) {
thisform.gender.focus();
return false;
}
}
function validate_gender(gender, error) {
var validGender = (gender === "M" || gender === "F")
if (!validGender) {
genderHelper.innerHTML = error
}
return validGender
}
Update
After playing with it for while in jsFiddle I've found the problem appears to be that your <span> tag is nested within the <select> tag, which is why you can't see it.
Here's a working version mostly using your code:
http://jsfiddle.net/6buUJ/1/
You can not display text in a select area that is not an option or a optgroup.
I think it better to :
add a span with 'A Valid gender is Required' close to select area and display it, when gender is not select.
or border in red the select area if gender mising.
You can't nest a span inside a select element.
You could however update one of the select elements to have the text you want the user to see.
Probably just having the span next to the select is the best though.
This is not valid html:
<select name="gender" ><span id="gender_help"></span>
<option value="0" selected="selected">Select...</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
"0".indexOf("0") is 0
"M".indexOf("0") is -1
"F".indexof("0") is -1
You could check if (value != '0') { return true; }

Categories

Resources