The site I'm building requires two identical forms on each page that sends the data to the same place, one form in the sidebar, and the other form in the footer. All I am trying for is light weight javascript that will kick out an error message if the user tries to submit the form when any or all of the required fields are left blank. Here's my issue:
Everything works as I intended for the sidebar form, however the javascript isn't treating the form placed in the footer as it does the sidebar form. When all form requirements are satisfied within form #2, it doesn't process the data and only shows the error message because I'm assuming it thinks the form is blank since the other form is blank.
I understand that there's likely a conflict of interest going on and the javascript engine is confused due to the input id's being exactly the same (they nned to be for this project since it involves salesforce). I already have bullet proof spam protection built into the php file that processes the form data, I just need some basic client-side validation to prevent the user from submitting the forms with any missing 'required' data. Like I said, everything works as I want it to with the first form, but not at all with the second. Can anyone help me with this because I don't really know where to start. I'm still relatively new to working with javascript so I apologize if what I have written is mess.
form #1 (in the sidebar)
$("#messageSent").hide();
$("#form1").submit(function(ev){
ev.preventDefault();
var fname = $('#first_name').val();
var lname = $('#last_name').val();
var phone = $('#phone').val();
var email = $('#email').val();
var condition = $('#condition').val();
var relationship = $('#relationship').val();
var inquiry = $('#inquiry').val();
if(fname && lname && phone && email && condition && relationship && inquiry){
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $("#form1").serialize(), // serializes the form's elements.
success: function(data)
{
data = $("#messageSent").fadeIn(),
$("#form1").fadeOut()
}
});
} else {
alert("You must complete the required fields before submitting the form.")
return false;
}
});
form #2 (in the footer section)
$('#messageSent-bottom').hide();
$("#form2").submit(function(ev){
ev.preventDefault();
var fname = $('#first_name').val();
var lname = $('#last_name').val();
var phone = $('#phone').val();
var email = $('#email').val();
var condition = $('#condition').val();
var relationship = $('#relationship').val();
var inquiry = $('#inquiry').val();
if(fname && lname && phone && email && condition && relationship && inquiry){
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $("#form2").serialize(), // serializes the form's elements.
success: function(data){
data = $("#messageSent-bottom").fadeIn(),
$("#form2").fadeOut()
}
});
} else {
alert("You must complete the required fields before submitting the form.")
return false;
}
});
When you use $('#the-id'), it only grabs the first one on the page (since you really shouldn't have multiple elements with the same id).
You could try adding something like the following:
var fname = $(this).find('#first_name').val();
This will keep it in the context of the current form. Though I would probably just prefix the ids since you already have separate submit functions.
Related
I have already built a form validator in JS, a portion of which is displayed below. I just need help in displaying an error and scrolling to the field.
Okay, so each <input> will have attributes specifying the validation they need, eg:
<input data-mandatory="yes" data-validation="phone" data-max-digits="10">
There attributes are parsed at the time of form submission, and if I come across an errornous field I need to scroll to that field and display an error in English (multilingual not needed).
var $form = $('#main-form');
$form.submit(function(event) {
event.preventDefault();
// per field
$form.find("input,textarea").each(function(f, field){
// read metadata
var type = $(field).attr("type");
var mandatory = $(field).data("mandatory");
var maxDigits = $(field).data("max-digits")) || 1000;
var validation = $(field).data("validation");
// read value
var value = $(field).value();
// process mandatory textfields
if (type == "text" || type == "number"){
var strValue = trim(value.toString());
if (mandatory && strValue.length == 0){
// HOW DO I SHOW AN ERROR AT THE CURRENT FIELD?
// and how do I scroll to it?
}
}
});
});
Edit: I've got a non-trivial amount of code in node.js (5K LOC) which I'm porting to the client side, which is required by my organization. That code is not displayed above.
Edit: I've looked online for an hour but the jQuery form validator libraries that I've seen do not function the way I need. I already have form sanitation & validation code (which supports various data types like phone number, ZIP code, etc) in Node.js which I'm just porting to the client side.
First of all i would recommend to use some free validation plugin. But, if you want for some reason to write it your self, than the answer to your question is:
First you need to have the error message hidden somewhere in your markup. There is a number of ways to do this. Most common solution would be something like that:
<div>
<input type="text" required />
<p class="error">Error</p>
</div>
Than you need to display it, in your example it could be done like this:
// process mandatory textfields
if (type == "text" || type == "number"){
var strValue = trim(value.toString());
if (mandatory && strValue.length == 0){
//show error
$(this).parent().find('.error').show();
//scroll
$('html, body').animate({
scrollTop: $(this).offset().top
}, 2000);
return; // stop validation(becouse you dont want to scroll more times)
}
}
You will need to figure out some more things (like hide all the errors before validating again), but this should answer your question.
I cannot get certain fields in a form to unlock. I have a javascript file that works on certain pages, but not on others.
I am using document.getElementById to target form fields to disable or enable them depending on certain inputs. It works fine on one page but not another. I have double checked all my ids and they are correct. Here is the javascript:
var pass2 = document.getElementById("password").value;
if (pass1 == pass2) {
//start profile
document.getElementById("premium-text").innerHTML = "Congratulations! You have unlocked the premium fields!";
document.getElementById("premium").style.background = "#d1fdd3";
document.getElementById("premium").style.borderColor = "#019408";
document.getElementById("description").disabled = false;
document.getElementById("fax-number").disabled = false;
document.getElementById("facebook-url").disabled = false;
document.getElementById("twitter-url").disabled = false;
document.getElementById("google-plus-url").disabled = false;
document.getElementById("linkedin-url").disabled = false;
document.getElementById("type").disabled = false;
document.getElementById("city").disabled = false;
document.getElementById("status").disabled = false;
document.getElementById("price").disabled = false;
document.getElementById("bedrooms").disabled = false;
document.getElementById("bathrooms").disabled = false;
document.getElementById("size").disabled = false;
document.getElementById("property-id").disabled = false;
document.getElementById("video-url").disabled = false;
document.getElementById("featured").disabled = false;
The only difference in the pages is one has the form fields in the template (form ids are directly in edit-profile.php) and the other page pulls in the form fields from a sub template that has the ids in it (submit-property.php pulls form fields from a sub template partials/templates/submit-form.php).
What do I need to do to target the fields that are pulled in from the sub-template? The id gets pulled into the page source code so I assumed the document.getElementById would work fine, but it is not for some reason.
On this page the javascript is working but not on this page. You have to create an account to have access to these pages. The user is test1 and pass is testpass.
The password to unlock the form fields is QuL7eD
Make sure you don't have same multiple ids. If you can post your code I'll be able to assist you better.
I split the Javascript into two seperate files and that seemed to work. I can only assume this had something to do with the fact that there were different field ids on each page and when the document.getElementById ran and didn't find all the ids (since some were on a different page) that is why it wasn't working.
I'm working on designing a new process for internal job submission for work which now involves javascript for it to work effectively.
Scripting is not my forte but that hasn't deterred me, I've been able to find three different pieces of code to insert into the various buttons and fields and they've done what they should do. My problem is I need to combine some of these for an extra validation on submit. This is where I fall short.
The process:
There is a required field in the form which currently runs a custom validation script to check a certain format specific to the code needed for a job. This runs well and I was even able to add an alert and hint images that show when incorrect and a little tick when correct. Beautiful.
The second major part of the form is in the submit button. I hacked together a code which not only emails the submitted form with fields as the subject line but also makes all fields read only before doing so. Brilliant.
Here's the messy part. A user can enter a correct or incorrect required code and the validator does its bit but that doesn't stop them from still submitting the form. Fine. I can fix that by running the validator again on the submit button so it not only gives user feedback on blur of the required field but again validates on submit so if the field is incorrect the submit stops until the user has the correct value in the field. This is where my knowledge stops like a cliff edge and I can't seem to build a bridge.
I've tried numerous ways of calling the field value then just running the same validation script with some if and else statements but it just doesn't work.
Can anyone help? Current code for submission button below but keep in mind that the validation section of this code is also attached to the required field directly (this affects it?):
function OR_Stuff() {
var ProjectTitle = getField("ProjectTitle").value;
var Brand = getField("Brand").value;
var Name = getField("Name").value;
var Noosh = getField("INT_NooshCode").value;
for (var i = 0 ; i < this.numFields ; i++) {
var f = this.getField(this.getNthFieldName(i));
if (f.type != "Submit") // Change f.type to button name in form that the action is applied to
{
f.readonly = true;
}
}
this.mailDoc({
cTo: "email",
cBcc: "email",
cSubject: "NEW JOB: "+Brand+" - "+ProjectTitle+" - "+Noosh,
cMsg: "Thanks "+Name+" for sending through this job."
});
}
var re = /^\d{5}[A-Z]\d{2}$/
if (re.test(INT_NooshCode.value) == false) {
this.getField("RequiredAlert").display = display.visible;
this.getField("NooshTick").display = display.hidden;
app.alert("Sorry, we can't start a project without a Noosh code. \n\nPlease enter a valid Noosh code EG: 34256P02");
}
else {
OR_Stuff();
}
I am trying to validate the form using javascript. Once the code below executes I want to get the the php from an external script to run without a page load with a success message after can anyone help?
The script below works fine and pulling the notEmpty from a seperate function. I need the script to then:
1. if there are no errors produced then pull the php and transfer data from each value listed.
2. Display a success message
var year = document.getElementById('year');
var period = document.getElementById('period');
var live = document.getElementById('live');
var start = document.getElementById('start');
var todate = document.getElementById('todate');
var sdeadline = document.getElementById('sdeadline');
var cdeadline = document.getElementById('cdeadline');
var circ = document.getElementById('circ');
var line = document.getElementById('line');
// Check each input in the order that it appears in the form!
if(notEmpty(year, "Please fill in Year")){
if(notEmpty(period, "Please fill in Period")){
if(notEmpty(live, "Please fill in live Date")){
if(notEmpty(start, "Please fill in Start Date")){
if(notEmpty(todate, "Please fill in End Date")){
if(notEmpty(sdeadline, "Please fill in Supplier Deadline")){
if(notEmpty(cdeadline, "Please fill in Commerical Deadline")){
if(notEmpty(circ, "Please fill in Circulars Due")){
if(notEmpty(line, "Please fill in Line Listing Downloads")){
}}}}}}}}}
return false;
The ideea is to create a string with data that you want to transfer to php script:
var datasend = 'year='+year+'&period='+period+'&live='+live+ ...;
Then, if no errors, calls an Ajax function that sends via Post the string to server.
See a tutorial about: AJAX with POST and PHP
Sorry for this most likely simple question.
I am running a script on submission of the form (code below), but first I would like to validate the form (contains one text box which must be an email) before the code is executed.
The script below is taken from here to ensure the form data is passed along to the colorbox lightbox script. But i only want to run this if the form is validated. I don't know how to combine this with an email validation script. Help! At the moment i've got a script that validates email (dreamweaver's) and this running, this command still runs even if it doesn't validate and i am not sure how to edit it so it doesn't.
$(document).ready(function() {
$("input#SearchButton").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
return url+'?'+ser;
}, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false});
});
Then I am using this to validate the form:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} }} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
Thanks!!!!
The HTML for the tigger is:
<input name="submit" type="image" onclick="MM_validateForm('email','','RisEmail');return document.MM_returnValue" src="images/go-button.gif" alt="Go! Get quote now!" align="top" : id="SearchButton"/>
In a nutshell: I want to tigger the code in the first snippet if the form validates using the code in the second snippet that is called by the html even in the third code snippet, but not if it doesn't.
You didn't post your HTML so I don't know if you have an actual form or just an input field without an actual form tag.
Assuming the former, you need a submit event so you can validate the form and then, if validation failed, terminate the submission.
$('#my_form').submit(function() {
//validate - forget the whole thing if it fails
if (!$('#my_field').val()) return false;
//if we get this far, validation succeeded - do other stuff now
});
A form submission is halted any time the submit callback returns false (or fires event.preventDefault()).
Andrew is correct, it would help if you provided the html in order to establish what the event trigger will be. Having reviewed the jquery plugin 'colorbox' briefly, it appears the lightbox is bound to the selectors click event.
Assuming Andrew's answer, if the email address validates you would need to manually trigger the click event for the lightbox from within the submit handler for the form. The following code should suffice.
$('#my_form').on('submit', function(e){
//perform validation.
MM_validateForm('email','','RisEmail');
//check the document variable set by the validation.
if (!document.MM_returnValue)
{
//did not validate
}else{
//open the colorbox
var search_btn = $('input#search');
search_btn.colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize();
return url + '?' + ser;
},
innerWidth: "1280",
innerHeight: "884px",
iframe:true,
scrolling:false});
//manually trigger the click event
search_btn.trigger('click');
}
//in either instance, disable the default action to ensure the form does not follow through.
e.preventDefault();
});
Obviously you'll have to replace the css selector names with your own, and utilise the email validation script that you may or may not have.