PHP form works on index but not contact us page - javascript

I have been developing a pretty simple mailer form in PHP. I have each of the questions in div elements and this javascript reveals the next div/question (it is in the file form.php)
<script type="text/javascript">
function hideshow(which){
if (!document.getElementById)
return if (which.style.display=="block")
which.style.display="none"
else which.style.display="block" }
</script>
and a separate code validates what was selected or inputted before revealing the next element.
Okay, so everything works just fine on the index page. However, on the contact us page (where I want the form available since I suspect many people will not fill out the popup on the index page) I have hit a snag. My script advances all the way to the final question and the button to submit the form. Then nothing happens... I can click the button but it does not submit the form. Here is the script that should submit the form (included in validation.js):
function ageValidate(){ 'use strict';
//Verfiy that submitter is not a robot
var age=document.getElementById('age').value;
if(age === ""){ // no answer, submit form
document.getElementById('ageErr').innerHTML = 'This is to validate that you are not a robot, please enter the correct answer to the problem.';
return false;
} else if (age === "5"){ // right answer
submitForm(); return true; } else { // wrong answer
document.getElementById('ageErr').innerHTML = 'Your answer is incorrect or you did not use the numeric format. 2 is valid, but two is not valid.'; } }
$(document).ready(function() { $(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
} }); });
function submitForm() { if (document.getElementsByName("serviceType")[0].value === "")
return false; else if (document.getElementsByName("numberPhones")[0].value === "")
return false; else if (document.getElementsByName("zip")[0].value === "")
return false; else if (document.getElementsByName("email")[0].value === "")
return false; else if (document.getElementsByName("name")[0].value === "")
return false; else if (document.getElementsByName("age")[0].value === "")
return false; else { document.forms["howHelp"].submit(); }
and the last question on the form in form.php:
<div id="q7" style="display:none">
<div class="how-help">
<h2>What is eight minus three?</h2>
<center><div>
<input type="text" name="age" id="age" value="<?php echo $age;?>">
</div><br/>
<div id="ageErr" name="ageErr" style="color: #000; background: #41b0cc; font-weight:700; width: 400px; height: auto; margin:0px; font-size:10pt;"></div></center>
</div>
<!-- FOOTER -->
<div class="how-help-footer">
<center>
<input type="button" class="jump"
value="Continue"
onclick="ageValidate()"></form>
</center>BACK<div class="private"> Privacy Policy</div>
</div>
</div>
<script src="validation.js" language="javascript" type="text/javascript"></script>
Again, it works perfectly fine on the index page but not the contact page...
I should add that all of the files are in the same directory so there should not be any issue with pointing to the wrong directory. I use
php include 'form.php'
to have the form both places and I am not sure if this could be the issue, but my form action is:
$_SERVER['PHP_SELF'];
I should add that this is an amazing community of extremely helpful people and without the many questions asked and answered I would not be where I am with this project, so thanks for everything in the past and in advance!

Because I was adding the form to a page that already had a comment form on it, the IDs of the two mailers were in conflict. Silly when I pull back and think about it. I've separated the two forms.

Related

Prevent Form from Submitting if there are Errors

Before I get into the problem details, I still need to tell you about this form I am creating. I have a Registration form and once the user submits the form by clicking the Submit button, it will NOT go directly to a Successfully Registered page. The user will be seeing a Confirmation page prior to that. In this page, the user will see all the data he inputted for him to review. Below it are the Confirm button and the Return button (if user still likes/needs to edit his details, it will then show the form for him to edit once this button is clicked). But here's the thing, the Registration form page and the Confirmation page are in just the same page. What I did is that when the user submits the form, it will hide some elements including the Submit button and then just show the details he inputted. When the user clicks the Return button on the Confirmation page, it will just then show again the hidden fields so the user can edit his details.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working. I am using bootstrap for my form so when there are errors, the input fields' borders would turn red and would obtain a class has-error. Here's what I did:
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
But again, it is not working. I also googled some jQueries like the .valid() and .validate() functions but I'm not really sure about it and also didn't work for me.
I also did this code where the Submit button should disable when required fields are still empty. And it is perfectly working:
$('#submit').attr('disabled',true);
$('input[id^="account"]').keyup(function() {
if(($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0)) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
I hope you understand my problem. I will make it clearer if this confuses you.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working.
When is it checking for errors? It needs to disable the submit button at the same time it is checking for errors. Your code doesn't work because there's no event telling it WHEN to execute. WHEN do you want submit button to be disabled?
Do you want it triggered when the field is validated or when the form is submitted?
You can't really tie it to the submit button unless you want to click it first to validate the form fields, and then again to submit validated fields. Then you'll need to figure out how to tell it that it's been validated like by a class, maybe? Only accept inputs that hasClass('valid')?
below are the changes
$(".form-group").find("td").each(function() {
if($(this).hasClass('has-error')) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
Try the following
$('#submit').click(function(){
var error = false;
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
error = true;
return false; //break out of .each
}
});
return !error;
});
You can achieve this by maintaining 2 sections.
1. Form section
<form id="form1">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="button" id="confirm" value="Confirm" />
</form>
2. Confirm section
<div id="disp_data" style="display: none;">
<lable>Name: <span id="name_val"></span></lable>
<lable>Email: <span id="email_val"></span></lable>
<input type="button" id="return" value="Return" />
<input type="button" id="submit" value="Submit" />
</div>
You have to submit the form by using js submit method on validating the form in confirm section (When the user clicks on submit button)
$("#submit").click(function(){
var error_cnt = false;
if($("#name").val() == '') {
error_cnt = true;
alert("Enter Name");
}
if($("#email").val() == '') {
error_cnt = true;
alert("Enter Email");
}
if(error_cnt == false) {
$("#form1").submit();
} else {
$("#disp_data").hide();
$("#form1").show();
}
Demo
You have to prevent the form from sumition by return back a boolean false so that it will stop the execution.
$('#submit').click(function(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
if(!ret) return false;
});
If you want to disable the submit button in case of any error you need to monitor the changes of each input fields. so better to give a class name to all those input fields like commonClass
then
function validation_check(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
return ret;
}
$("#submit").prop("disabled",true)
$(".commonClass").change(function(){
if(validation_check()){
$("#submit").prop("disabled",false)
}
else {
$("#submit").prop("disabled",true)
}
});
please use onsubmit attribute in the form element and write a javascript function to return false when there is any error. I've added fiddle you can try.
HTML FORM
<form action="" method="" onsubmit="return dosubmit();">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="submit" value="Submit" />
</form>
JAVASCRIPT
function dosubmit() {
if(false) { //Check for errors, if there are errors return false. This will prevent th form being submitted.
return false;
} else {
return true;
}
}
Let me know if this fixes your issue.

Validate form's textarea - jQuery

I am trying to develope a plugin for an application that let the users invite their friends to use the application by just sending an email. Juts like Dropbox does to let the users invite friends and receive extra space.
I am trying to validate the only field I have in the form (textarea) with JQuery (I am new to JQuery) before submiting it and be handled by php.
This textarea will contain email addresses, separated by commas if more than one. Not even sure if textarea is the best to use for what I am trying to accomplish. Anyway here is my form code:
<form id="colleagues" action="email-sent.php" method="POST">
<input type="hidden" name="user" value="user" />
<textarea id="emails" name="emails" value="emails" placeholder="Example: john#mail.com, thiffany#mail.com, scott#mail.com..."></textarea>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
Here is what I tried in Jquery with no success:
//handle error
$(function() {
$("#error_message").hide();
var error_emails = false;
$("#emails").focusout(function() {
check_email();
});
function check_email() {
if(your_string.indexOf('#') != -1) {
$("#error_message").hide();
} else {
$("#error_message").html("Invalid email form.Example:john#mail.com, thiffany#mail.com, scott#mail.com...");
$("#error_message").show();
error_emails = true;
}
}
$("#colleagues").submit(function() {
error_message = false;
check_email();
if(error_message == false) {
return true;
} else {
return false;
}
});
I hope the question was clear enough, if you need more info please let me know.
Many thanks in advance for all your help and advises.
var array = str.split(/,\s*/);
array.every(function(){
if(!validateEmail(curr)){
// email is not valid!
return false;
}
})
// Code from the famous Email validation
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Few errors as I noted down:
The code snippet posted here has missing braces }); at the end.
Also, what is your_string variable in the function check_email.
Also, error_message is assigned false always so the submit method will return true always.
Fixing this issues should help you.
I would use, as I commented above, append() or prepend() and just add fields. As mentioned in another post, client side use jQuery validation, but you should for sure validate server-side using a loop and filter_var($email, FILTER_VALIDATE_EMAIL). Here is a really basic example of the prepend():
<form id="colleagues" action="" method="POST">
<input type="hidden" name="user" value="user" />
<input name="emails[]" id="starter" placeholder="Email address" />
<div id="addEmail">+</div>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
<script>
$(document).ready(function() {
$("#addEmail").click(function() {
$("#colleagues").prepend('<input name="emails[]" placeholder="Email address" />');
});
});
</script>
Hi please use below js code,
$('#emails').focusout(function(e) {
var email_list = $('#emails').val();
var email_list_array = new Array();
email_list_array = email_list.split(",");
var invalid_email_list=' ';
$.each(email_list_array, function( index, value ) {
if(!validEmail(value))
{
invalid_email_list=invalid_email_list+' '+value+',';
}
});
console.log(invalid_email_list+' is not correct format.');
alert(invalid_email_list+' is not correct format.');
})
function validEmail(v) {
var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return (v.match(r) == null) ? false : true;
}
If you need to check more REGEX just do it validEmail() function. I hope this will help to sort out.
thank you
Your code might look correct, but you are using bad technique. My advice is to use jquery validation plugin that would handle textarea validation.for you. Also notice. There might be many solutions for this problem, but you should stick with simple one. And the first problem i see stright away is: button tag doesnt have type attribute. You are changing #error_message html, not text. Etc...

Javascript code not working unless there are no spaces. Why?

Ok so I am running into a really weird bug on my Wordpress site that hope is just my ignorance because this just seems too weird.
So I am working with styling a couple of input tags as well as a ReCaptcha form. I found some documentation at https://developers.google.com/recaptcha/old/docs/customization that I have been following. Basically what I want is the clean theme listed at that link and to do some showing/hiding of the captcha based on certain events.
I do realize that the top of the article mentions this version of the api is old, but the plugin I am using has some recaptcha code entangled in their code, so I figured I would try this first instead of making major modifications to the plugin.
So here is the code I am using
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
<!-- End code added by me -->
<script>
function validateGoodNewsUser(frm, requireName) {
requireName = requireName || false;
if(requireName && frm.goodnews_name.value=="") {
alert("Please provide name");
frm.goodnews_name.focus();
return false;
}
if(frm.email.value=="" || frm.email.value.indexOf("#")<1 || frm.email.value.indexOf(".")<1) {
alert("Please provide a valid email address");
frm.email.focus();
return false;
}
// check custom fields
var req_cnt = frm.elements["required_fields[]"].length; // there's always at least 1
if(req_cnt > 1) {
for(i = 0; i<req_cnt; i++) {
var fieldName = frm.elements["required_fields[]"][i].value;
if(fieldName !='') {
var isFilled = false;
// ignore radios
if(frm.elements[fieldName].type == 'radio') continue;
// checkbox
if(frm.elements[fieldName].type == 'checkbox' && !frm.elements[fieldName].checked) {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
// all other fields
if(frm.elements[fieldName].value=="") {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
}
}
}
return true;
}
</script>
<form method="post" class="goodnews-front-form" onsubmit="return validateGoodNewsUser(this,false);">
<div><label>Your Name:</label> <input type="text" name="goodnews_name"></div>
<div><label>*Your Email:</label> <input type="text" name="email" onfocus="toggleCaptcha(this)"></div>
<p><script type="text/javascript" src="<!--Captcha api url here-->"></script>
<noscript>
<iframe src="<!--Captcha api url here-->" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript></p>
<div><br>
<input type="submit" value="Subscribe">
</div>
<input type="hidden" name="goodnews_subscribe" value="1">
<input type="hidden" name="list_id" value="1">
<input type="hidden" name="required_fields[]" value="">
</form>
So the problem I am running into is when I load the page, I see the clean theme for ReCaptcha and the alert shows up when I click inside the input box for the email. But if I change my added code by adding a single space like this
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
<<<<<<<< Single new line space added.
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
The whole thing breaks and the page loads with the standard red ReCaptcha and my functions don't get called.
I don't mind not using spaces, but that seems very odd that a space would make the difference. Am I missing something here? Is this caused by the outdated api?
Edit:
I was asked to try to get a jsfiddle working (or not working???). I stripped out everything except the form and the function call. Even the ReCaptcha was taken out and I still can not get it to call the function. This may be my lack of knowledge on jsfiddle or it may get closer to the real problem. https://jsfiddle.net/b257779t/

make a field mandatory using javascript

I am trying to make a select field mandatory on a web page. I know how to do it with help of JS and form attribute 'onsubmit' and returning the function. But the problem is that form code is already written and I dont know how to add attribute now. Let me know if I can append attribute dynamically from JS.
The other way I tried is to call the JS after page loaded. But this isnt making the field mandatory and form can be submitted.
Following is my code..
<!DOCTYPE html>
<html>
<head>
<script>
function f1()
{
var countryValue = document.getElementById('count ID').value;
if (countryValue == "")
{
alert("field value missing");
return false;
}
var stateValue = document.getElementById('state ID').value;
if (stateValue == "")
{
alert("state field value missing");
return false;
}
}
</script>
</head>
<body>
<form method = "post" action = "33.html">
Country: <input type="text" id="count ID">
state: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
<br>
<input type = "submit">
</form>
<script>window.onload=f1</script>
</body>
</html>
Please help.
Have a look at this since you have messed up the IDs
Live Demo
window.onload=function() {
document.forms[0].onsubmit=function() { // first form on page
var countryValue = this.elements[0].value; // first field in form
if (countryValue == "") {
alert("Please enter a country");
return false;
}
var stateIdx = this.elements[1].selectedIndex; // second field
if (stateIdx < 1) { // your first option does not have a value
alert("Please select a state");
return false;
}
return true; // allow submission
}
}
PS: It is likely that POSTing to an html page will give you an error
To get the last button to do the submission
window.onload=function() {
var form = document.forms[0]; // first form
// last element in form:
form.elements[form.elements.length-1].onclick=function() {
...
...
...
this.form.submit(); // instead of return true
}
}
Once you've got a function to detect improper values (empty mandatory field or anything else, like a bad e-mail address for instance) you have a few different options :
disable the submit button
cancel the onclick event on the button
cancel the submit event on the form
disabling the submit button can be annoying for the user (it might flash on and off while the values are entered).
I had the same issue, but i made a extension. Using hook system to translate fields with "*", in the names, to validate like required field. This is a simple solution not intrusive where is not required addition of fields in the database, only by the use of sufix "*" in configuration of custom fields.
There is the code: https://github.com/voiski/bugzilla-required-field

How to ensure my confirm checkbox is ticked before allowing submission of my form

Once again the novice JS is back again with a question. I want a confirmation tickbox at the end of my form before allowing the user to send me their details and if it's not ticked then they can't submit the form. I've had a look on here and tried using different examples of coding but I just find it all very confusing after looking at 10 or 20 pages of different code. Here is what I've written so far, from what I can make out my form just skips over my checkbox validation code which is obviously what I don't want to happen:
<head>
<script>
function validate (){
send = document.getElementById("confirm").value;
errors = "";
if (send.checked == false){
errors += "Please tick the checkbox as confirmation your details are correct \n";
} else if (errors == ""){
alert ("Your details are being sent)
} else {
alert(errors);
}
}
</script>
</head>
<body>
<div>
<label for="confirm" class="fixedwidth">Yes I confirm all my details are correct</label>
<input type="checkbox" name="confirm" id="confirm"/>
</div>
<div class="button">
<input type="submit" value="SUBMIT" onclick="validate()"/>
</div>
I would just enable/disable your button based on the checkbox state. Add an ID to your button, (i'll pretend the submit button has an id of btnSubmit)
document.getElementById("confirm").onchange = function() {
document.getElementById("btnSubmit").disabled = !this.checked;
}
Demo: http://jsfiddle.net/tymeJV/hQ8hF/1
you are making send be confirm's value.
send = document.getElementById("confirm").value;
This way send.checked will not work. Because you are trying to get the attribute checked from a value (probably, string).
For the correct use, try this:
send = document.getElementById("confirm");
sendValue = send.value;
sendCheck = send.checked;
Then you can test with
if (sendCheck == false){ //sendCheck evaluate true if checkbox is checked, false if not.
To stop form from submitting, return false; after the error alerts.
Here the complete code - updated to work correctly (considering the <form> tag has id tesForm):
document.getElementById("testForm").onsubmit = function () {
var send = document.getElementById("confirm"),
sendValue = send.value,
sendCheck = send.checked,
errors = "";
//validate checkbox
if (!sendCheck) {
errors += "Please tick the checkbox as confirmation your details are correct \n";
}
//validate other stuff here
//in case you added more error types above
//stacked all errors and in the end, show them
if (errors != "") {
alert(errors);
return false; //if return, below code will not run
}
//passed all validations, then it's ok
alert("Your details are being sent"); // <- had a missing " after sent.
return true; //will submit
}
Fiddle: http://jsfiddle.net/RaphaelDDL/gHNAf/
You don't need javascript to do this. All modern browsers have native form validation built in. If you mark the checkbox as required, the form will not submit unless it is checked.
<form>
<input type="checkbox" required=""/>
<button type="submit">Done</button>
</form>

Categories

Resources