Trying to clear an error prompt using JQuery - javascript

I am trying to clear an error icon on keydown.
** EDIT - adding the HTML **
<input class="validate" type="text" data-type="string" id="address" />
<input class="validate" type="text" data-type="number" id="zip" />
** END EDIT - Unsure if this will help shed some light **
Currently, the error displays using this function:
function validateFields(){
$(".validate").blur(function(){
var status = "";
var label = this.id;
var value = this.value;
if(value != ""){
status = "good";
console.log("status " + status);
}
else{
status = "error";
console.log("status " + status);
}
if(status == "good"){
label.html(label.html()+' ✅');
}
if(status == "error"){
label.html(label.html()+' ❌');
}
});
}
If status equals Error, show the error icon.
So now, I want to clear the error when the user keydowns. Here is my attempt:
function clearError(){
$(".validate").keydown(function(){
var datatype = $(this).data("type");
var label = this.id;
label.html(label.html()+' ');
});
}
Obviously, I am not having much success clearing the error using the above keydown function.
How can I make this work?

The label business with trying to keep the text inside is not very intuitive, so I added span to your label so you remove and add error symbols from the span in your functions. Additionally, you had some unnecessary code that could be removed in both functions. For example, your if statements checking status were unnecessary since you already checked if the value was empty (where you set the status), therefore you could move that code into the if statement checking for empty values.
We set each corresponding span's id to the id of the input with "Span" id="testSpan", so it can be easily accessible by the JS functions. Remember inside jQuery functions this always refers to the non-jQuery object, so you can use the JS vanilla methods on it.
This is what I could come up with:
$(".validate").blur(function () {
var id = this.id; // get id
if (this.value != "") { // check if input is empty
document.getElementById(id + "Span").innerHTML = '✅'; //set ok symbol
console.log("good");
} else {
document.getElementById(id + "Span").innerHTML = '❌'; // set error symbol
console.log("error empty text");
}
});
$(".validate").keydown(function () {
// if value is empty set error symbol, otherwise nothing (keep ok symbol)
if (this.value === "") document.getElementById(this.id + "Span").textContent = "";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="test">test<span id="testSpan"></span></label>
<input id="test" class="validate">
<label for="test2">test<span id="test2Span"></span></label>
<input id="test2" class="validate">

Related

How to add more than 2 conditions in an If/Else statement in Javascript?

Me again.
So I have been working on this basic search functionality where I am comparing the value entered as text with a list of other values and doing an action based on it.
In simpler words. I am making a search where the logic compares the value with other strings and if the comparison is successful then show and hide and vice versa if the condition is false.
Now the other condition i want to implement is that when the text bar(where the user will enter the value) is empty then both the divs should be shown. Below is my code for this:
HTML where I am getting the value from: - Im using the onchange to get the value - oninput is not working :(
<label>Find your location:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..."
onChange="myFunction()"/>
And This is my JS code
<script>
function myFunction() {
var inzone = document.getElementById("inzone");
var outzone = document.getElementById("outzone");
if(document.getElementById("search_input").value == null
||document.getElementById("search_input").value == "")
{
outzone.style.display = "";
inzone.style.display = "";
}
else if (document.getElementById("search_input").value === 'something something')
{
outzone.style.display = "none";
inzone.style.display = "";
}
else {
inzone.style.display = "none";
outzone.style.display = "";
}
document.getElementById("search_input").value == null will never be true. The value property of an HTMLInputElement is always a string. It may be "", but not null or undefined (the two things == null checks).

Implementing jQuery AJAX from within Javascript

I used a tutorial from css-tricks to help me with HTML5 Constraint Validation for my application's client-side validation. I would like to introduce an AJAX script that submits the form to prevent reloading the page (as the form is displayed in a modal pop-up that I don't want closing on submit.)
From what I have gathered online, it seems the best way to do this is to use jQuery. However, the validation script is written in regular ol' Javascript.
I'm kind of confused as to how to implement this within my validation script so that I don't need to make another http request to a separate js file (not even sure if that's an option, as I kind of need it to work seamlessly with the existing script). Do I just call jQuery inside the existing script to prevent conflicts (as shown below?) Do I need to wrap the entire script in the ready event?
Currently, I'm not sure why this isn't working. The form still submits and reloads the page, so it seems to be ignoring the Ajax submit function.
The following includes the form markup from its PHP class and the form.validate.js file used for validation and ajax:
function copyTxtVal(bf) {
if(bf.samecheck.checked == true) {
bf.contact_name_first.value = bf.cpap_sup_name_first.value;
bf.contact_name_last.value = bf.cpap_sup_name_last.value;
} else {
bf.contact_name_first.value = '';
bf.contact_name_last.value = '';
}
}
// Add the novalidate attribute when the JS loads
var forms = document.querySelectorAll('.validate');
for (var i = 0; i < forms.length; i++) {
forms[i].setAttribute('novalidate', true);
}
// Validate the field
var hasError = function (field) {
// Don't validate submits, buttons, file and reset inputs, and disabled fields
if(field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') return;
// Get Validity
var validity = field.validity;
// Get valid, return null
if(validity.valid) return;
// If field is required and empty
if (validity.valueMissing) return 'Please fill out this field.';
// If not the right type
if (validity.typeMismatch) {
if(field.type === 'email') return 'Please enter an email address.';
if(field.type === 'url') return 'Please enter a URL.';
}
// If too short
if (validity.tooShort) return 'Please lengthen this text to ' + field.getAttribute('minLength') + ' characters or more. You are currently using ' + field.value.length + ' characters.';
// If too long
if (validity.tooLong) return 'Please short this text to no more than ' + field.getAttribute('maxLength') + ' characters. You are currently using ' + field.value.length + ' characters.';
// If number input isn't a number
if (validity.badInput) return 'Please enter a number.';
// If a number value doesn't match the step interval
if (validity.stepMismatch) return 'Please select a valid value.';
// If a number field is over the max
if (validity.rangeOverflow) return 'Please select a smaller value.';
// If a number field is below the min
if (validity.rangeUnderflow) return 'Please select a larger value.';
// If pattern doesn't match
if (validity.patternMismatch) {
// If pattern info is included, return custom error
if (field.hasAttribute('title')) return field.getAttribute('title');
// Otherwise, generic error
return 'Please match the requested format.';
}
// If all else fails, return a generic catchall error
return 'The value you entered for this field is invalid.';
};
var showError = function(field, error){
// Add error class to field
field.classList.add('error');
// Get field id or name
var id = field.id || field.name;
if (!id) return;
// Check if error message field already exists
// If not, create one
var message = field.form.querySelector('.error-message#error-for-' + id );
if (!message) {
message = document.createElement('div');
message.className = 'error-message';
message.id = 'error-for-' + id;
field.parentNode.insertBefore( message, field.nextSibling );
}
// Add ARIA role to the field
field.setAttribute('aria-describedby', 'error-for-' + id);
// Update error message
message.innerHTML = error;
// Show error message
message.style.display = 'block';
message.style.visibility = 'visible';
}
var removeError = function(field) {
// Remove the error message
// Remove error class to field
field.classList.remove('error');
// Remove ARIA role from the field
field.removeAttribute('aria-describedby');
// Get field id or name
var id = field.id || field.name;
if (!id) return;
// Check if an error message is in the DOM
var message = field.form.querySelector('.error-message#error-for-' + id + '');
if (!message) return;
// If so, hide it
message.innerHTML = '';
message.style.display = 'none';
message.style.visibility = 'hidden';
};
//Listen to all blur events
document.addEventListener('blur', function (event) {
// Only run if field is in a form to be validated by our custom script
if (!event.target.form.classList.contains('validate')) return;
// Validate field
var error = hasError(event.target);
// If there's an error, show it
if(error){
showError(event.target, error);
return;
}
//Otherwise, remove any existing error msg
removeError(event.target);
}, true);
// Check all fields on submit
document.addEventListener('submit', function (event) {
// Only run on forms flagged for validation
if (!event.target.classList.contains('validate')) return;
// Get all of the form elements
var fields = event.target.elements;
// Validate each field
// Store the first field with an error to a variable so we can bring it into focus later
var error, hasErrors;
for (var i = 0; i < fields.length; i++) {
error = hasError(fields[i]);
if (error) {
showError(fields[i], error);
if (!hasErrors) {
hasErrors = fields[i];
}
}
}
// If there are errors, don't submit form and focus on first element with error
if (hasErrors) {
event.preventDefault();
hasErrors.focus();
}
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else {
(function($){
var form = $('#cpapsupform');
var formMessages = $('#cpap-form-messages');
// Is this line below necessary if I've done this in the normal js above?
$(form).submit(function(event){
event.preventDefault();
// Serialize Form Data
var formData = $(form).serialize();
//Submit the form via AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#cpap_sup_name_first').val('');
$('#cpap_sup_name_last').val('');
$('#contact_name_first').val('');
$('#contact_name_last').val('');
$('#cpap_contact_email').val('');
$('#cpap_contact_phone').val('');
$('#cpap_patient_dob').val('');
$('#cpap_patient_zip').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('An error occured and your message could not be sent.');
}
});
});
})(jQuery);
}
}, false);
Here is the form markup (excerpted from the php form class I am using):
<?php
<div id="cpap-form-area">
<div id="cpap-form-messages"></div>
<div class="cpap-form-greet">
<p>Some text goes here.</p>
</div>
<form method="POST" action="" id="cpapsupform" class="validate" enctype="multipart/form-data" >
<fieldset>
<legend>Patient Name</legend>
<div class="p-firstname">
<label for="cpap_sup_name_first">First Name:</label>
<input type="text" size="50" name="cpap_sup_name_first" id="cpap_sup_name_first" value="<?php echo $display['cpap_sup_name_first']; ?>" required />
</div>
<div class="p-lastname">
<label for="cpap_sup_name_last">Last Name:</label>
<input type="text" size="50" name="cpap_sup_name_last" id="cpap_sup_name_last" value="<?php echo $display['cpap_sup_name_last']; ?>" required />
</div>
</fieldset>
<fieldset>
<legend>Point of Contact</legend>
<div class="samename">
<div class="cpap_input_alt">
<input id="samecheck" type="checkbox" name="samecheck" onchange="copyTxtVal(this.form);">
</div>
<label for="samecheck">Use same as above</label>
</div>
<div class="c-firstname">
<label for="contact_name_first">First Name:</label>
<input type="text" size="50" name="contact_name_first" id="contact_name_first" value="<?php echo $display['contact_name_first']; ?>" required />
</div>
<div class="c-lastname">
<label for="contact_name_last">Last Name:</label>
<input type="text" size="50" name="contact_name_last" id="contact_name_last" value="<?php echo $display['contact_name_last']; ?>" required />
</div>
</fieldset>
<fieldset>
<legend>Contact Details</legend>
<div class="cpap-email-contact">
<label for="cpap_contact_email">Email:</label>
<input type="email" name="cpap_contact_email" id="cpap_contact_email" value="<?php echo $display['cpap_contact_email']; ?>" title="The domain portion of the email after '#' is invalid." pattern="^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*(\.\w{2,})+$" required />
</div>
<div class="cpap-tel-contact">
<label for="cpap_contact_phone">Phone:<br /><span class="tiny-txt">(10 digits; no spaces)</span></label>
<input type="text" maxlength="10" name="cpap_contact_phone" id="cpap_contact_phone" value="<?php echo $display['cpap_contact_phone']; ?>" pattern="\d{10}" required />
</div>
</fieldset>
<fieldset>
<legend>Patient Date of Birth</legend>
<div class="cpap-dob">
<label for="cpap_patient_dob">Birthdate: <br /><span class="tiny-txt">(MM/DD/YYYY)</span></label>
<input type="text" name="cpap_patient_dob" id="cpap_patient_dob" value="<?php echo $display['cpap_patient_dob']; ?>" title="Your date looks incorrect, or it doesn't match the required format." max-length="10" pattern="((0[1-9])|(1[0-2]))/(([0-2]\d)|([3][01]))/((19|20)\d{2})" required ></input>
</div>
</fieldset>
<fieldset>
<legend>Address Info</legend>
<div class="cpap-zip">
<label for="cpap_patient_zip">Patient Zipcode:<br /><span class="tiny-txt">(first 5 digits only)</span></label>
<input type="text" maxlength="5" name="cpap_patient_zip" id="cpap_patient_zip" value="<?php echo $display['cpap_patient_zip']; ?>" required ></input>
</div>
</fieldset>
<button type="submit" id="cpapAjaxButton" name="cpapAjaxButton">Submit Request</button>
<p class="form-msg">All fields must be completed</p>
<div class="clearfix"></div>
<?php wp_nonce_field('submit_cpap_form','nonce_field_for_submit_cpap_form'); ?>
</form>
</div>
First, you do have a syntax error in that you are missing the opening curly brace of your else branch right here:
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else (function($){
It should be:
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else { (function($){
And, to avoid these kinds of errors, good indentation and formatting of code goes a long way, so really, this would be the best way to write it:
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else {
(function($) {
Now, to you main point. As long as you have referenced the JQuery library prior to your code needing to use it, you just go ahead and use JQuery when and where you need to. If you need some page initialization work done, then yes, a "document ready" function should be passed into the JQuery object. But, apart from that, you can leverage JQuery whenever you need to so the self-invoking function you have inside of your else branch is redundant - - if code execution enters that branch, you don't invoke JQuery again, you just use it.
Also, you start off with:
document.addEventListener('submit', function (event) {
But, the document object doesn't have a submit event. The event listener should be set up on the form element that is going to be submitted.
You also have some unnecessary variables and in a couple of cases, you set your variables equal to JQuery objects, but then passed those objects into the JQuery object again later as if they were regular DOM objects.
Here is your cleaned up code. Check the comments carefully for what changes were made and why. Also, this is the best we can do with answers since you didn't provide the hasError and showError functions and your HTML as well.
// The document object doesn't get submitted, the form does.
// Also this sytax finds every form that has the "validate" class,
// so there is no need to test for that in the callback function
$("form.validate").on('submit', function (event) {
// Get all of the form elements
var fields = event.target.elements;
// Always initialize your variables. Set them to null if you don't know the value to use yet
// Also, the "error" and "hasError" variables are not needed. You'll see why in a couple of lines down.
var hasErrors = null;
for (var i = 0; i < fields.length; i++) {
// I'm assuming you have a working "hasError" function that returns a boolean
// So, just take that return value and make that the basis for the if condition -- no
// need to store it just to test it on the next line.
if (hasError(fields[i])) {
// I'm assuming you have a working "showError" function. If we've entered into this
// branch of the code, we know that "hasError" returned true, so we can just pass that
// directly into the "showError" function instead of the "error" variable that we've
// now gotten rid of.
showError(fields[i], true);
// No need to test here. There is an error.
hasErrors = fields[i];
}
}
// If there are errors, don't submit form and focus on first element with error
if (hasErrors) {
event.preventDefault();
hasErrors.focus();
} else {
// You don't need a self-invoking function here. Just write the code that should execute
// It is a common convention to name variables that store references to JQuery objects
// with a leading $ to distinguish them as such and not regular DOM objects
var $form = $('#cpapsupform');
var $formMessages = $('#cpap-form-messages');
// Submit the form via AJAX
$.ajax({
type: 'POST',
url: $form.attr('action'), // $form is already a JQuery object, don't pass it to JQuery again
data: $form.serialize() // <-- You had semi-colon here, which you shouldn't have
}).done(function(response) {
// $formMessages is already a JQuery object, don't pass it to JQuery again
$formMessages.removeClass('error');
$formMessages.addClass('success');
// Set the message text.
$formMessages.text(response);
// Just use the DOM form.reset() method here instead of resetting each form field
$form[0].reset();
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$formMessages.removeClass('success');
$formMessages.addClass('error');
// Set the message text.
if (data.responseText !== '') {
$formMessages.text(data.responseText);
} else {
$formMessages.text('An error occured and your message could not be sent.');
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" class="validate">
<input type="text" id="name">
<input type="submit">
</form>
<form action="#" method="GET">
<input type="text" id="name">
<input type="submit">
</form>
jQuery IS Javascript, so of course you can use them together. I think your problem might lie in you not properly bracketing your else statement:
else { (function($){ // was missing brace after 'else'
var form = $('#cpapsupform');
var formMessages = $('#cpap-form-messages');
....
})(jQuery);
}//closing else brace

How to get value of dynamically generated textbox with same id using AJAX/PHP?

In this webpage I am generating multiple textbox dynamically and each textbox is meant to hold unique value and I want to get that value dynamically.But I'm not being able to catch the value of the textbox according to its position. This code is only working for the firstly generated textbox. I have code like this
<tr>
<td align="center"><input type="text" name="serialNoArray[]" id="serialArray" onChange="checkusername()" ><span id="std_id_status"></span></td>
</tr>
<script>
function checkusername() {
var s = _("serialArray").value;
if(s != "") {
_("std_id_status").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true){
_("std_id_status").innerHTML = ajax.responseText;
}
}
ajax.send("std_id_check="+s);
}
}
</script>
First you should use classes not id, because an element with id must be unique for the entire document.
And since you use onChange you can pass the element using this like that onChange="checkusername(this)" .
I guess you should also change the code of the restrict function onkeyup="restrict('serialArray')" also but i do not see that code so I cannot help you more if you do not provide this code too...
<tr>
<td align="center"><input type="text" name="serialNoArray[]" class="serialArray" onkeyup="restrict('serialArray')" onChange="checkusername(this)" ><span class="std_id_status"></span></td>
</tr>
Then you can get only the value of the element being changed and change the html of the matching span only.(I use jQuery in the example so you should include it in your document.)
<script>
function checkusername(s) {
if (s.value != "") {
$(s).nextAll('.std_id_status').first().html('checking ...');
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
$(s).nextAll('.std_id_status').first().html(ajax.responseText);
}
}
ajax.send("std_id_check=" + s.value);
}
}
</script>
Since i do not have all your javascript code I could not test it but something like this should work.
I have not tested but this should do it
All the dynamically generated textboxes, give them a class
<input type="text" class="tagMe" placeholder="Enter Serial No." onkeypress="return isNumberKey2(event)" onkeyup="restrict('serialArray')" onChange="checkusername()" required autofocus >
Collecting the data
var info= "";
$('.tagMe').each( obj, function( key, value ) {
if(info != "")
info += "^"; // ^ is a delimiter
info += value;
});
Send info to your server, split on ^ and parse data (careful of empty elements)

Passing an id through a function parameter

Trying to get a value of a textbox by passing the ID into a function parameter. Should be easy but can't wrap my head around it.
JavaScript:
function checkfield(id)
{
var field = document.getElementById(id);
if (isNaN(field) == true)
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(textbox);
field.select(textbox);
return false;
}
return true;
}
HTML:
<input type="text" id="numbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield('numbox19')"/>
Error Message
Error: Unable to get property 'value' of undefined or null reference
Your ID is 19, but you're passing numberbox19 to the Javascript function. There are also several syntax errors.
Try:
<input type="text" id="numberbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield(this)"/>
And Javascript:
function checkfield(field) // <-- we passed the field in directly from the HTML, using 'this'
{
alert(field.value);
if (isNaN(field.value)) // check the value, not the field itself!
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(); // not "field.focus(textbox);"
return false;
}
return true;
}
The good thing here is, if you ever decide to change the ID for any reason, you only have to change it in one place instead of two.
the id of your input is "19" not "numberbox19"

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

Categories

Resources