I have a form that displays a box that has two options, one is "accepted" and the other "not accept". It turns out that when the user uses to send the email, he can send it with the button marked "not accept". Is there any way that I can make it validate?
HTML
<div class="form">
<h4>Valor do consórcio: <span class="slider-value quote-form-element" data-name="Valor | Automóvel" data-slider-id="consorcio-auto">R$ <span></span></span></h4>
<div class="slider" data-slider-min="20000" data-slider-max="100000" data-slider-start="23192" data-slider-step="1000" data-slider-id="consorcio-auto"></div>
<h4>Seus dados:</h4>
<input type="text" name="Nome" placeholder="Nome..." class="quote-form-element" />
<input type="text" name="Cidade" placeholder="Cidade/UF..." class="quote-form-element quote-form-client-email last" />
<input type="text" name="Número de Telefone" placeholder="Telefone..." class="quote-form-element telefone" />
<input type="text" name="Endereço de Email" placeholder="E-mail..." class="quote-form-element quote-form-client-email last contact_email" />
<h4>Política de Privacidade</h4>
<div class="checkbox quote-form-element" data-checked="yes" data-name="Política de Privacidade">
<span class="checkbox-status"><i class="fa fa-check"></i></span>
<span class="checkbox-values">
<span class="checkbox-value-checked" style="font-size: 12px">Li e aceito a politica de privacidade</span>
<span class="checkbox-value-unchecked">Não aceito</span>
</span>
</div>
<button class="button button-navy-blue send-quote" type="button">Simular meu consórcio <i class="fa fa-paper-plane-o"></i></button>
<div class="quote-form-thanks">
<div class="quote-form-thanks-content">
Obrigado pelo seu interesse, retornaremos em breve ;).
<span class="quote-form-thanks-close">Fechar</span>
</div>
</div>
</div>
Javascript
$('.send-quote').click(function () {
var quoteForm = $(this).parent();
var quoteFormParent = quoteForm.parent().parent();
var insuranceType = quoteFormParent.data('quote-form-for');
var fields = {};
var fieldID = 0;
var fieldName = '';
var fieldValue = '';
var clientName = '';
var clientEmail = '';
var errorFound = false;
quoteForm.find('.quote-form-element').each(function (fieldID) {
fieldName = $(this).attr('name');
if (typeof fieldName == 'undefined' || fieldName === false) {
fieldName = $(this).data('name');
}
if ($(this).hasClass('checkbox')) {
fieldValue = $(this).data('checked') == 'yes' ? $(this).children('.checkbox-values').children('.checkbox-value-checked').text() : $(this).children('.checkbox-values').children('.checkbox-value-unchecked').text();
}
else {
fieldValue = $(this).is('input') || $(this).is('select') ? $(this).val() : $(this).text();
if (($(this).is('input') && fieldValue == '') || ($(this).is('select') && fieldValue == '-')) {
errorFound = true;
$(this).addClass('error');
}
else {
$(this).removeClass('error');
}
}
if ($(this).hasClass('quote-form-client-name')) clientName = $(this).val();
if ($(this).hasClass('quote-form-client-email')) clientEmail = $(this).val();
fields[fieldID] = { 'name': fieldName, 'value': fieldValue };
fieldID++;
});
if (errorFound == false) {
$.ajax({
url: '_assets/submit.php',
data: { 'send': 'quote-form', 'values': fields, 'clientName': clientName, 'clientEmail': clientEmail },
type: 'post',
success: function (output) {
quoteForm.children('.quote-form-thanks').fadeIn(300);
}
});
}
});
page that displays the contents in the "Simulation".
So you need to check if "no accept" is checked or not using radio inputs.
$('.send-quote').click(function() {
if ($('[name=terms]:checked').val() === 'no') {
console.log('got an error');
} else {
console.log('all good');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="terms" value="yes" checked></input>
<label for="terms">Do accept terms</label>
<br>
<input type="radio" name="terms" value="no"></input>
<label for="terms">Don't accept terms</label>
<br>
<button type="button" class="send-quote">Send Quote</button>
Related
I have problems with my form submittiting even if the fields are not valid.
I've tried a lot of different code, but I'm currently with this.
const form = document.getElementById('kontaktskjema');
const email = document.getElementById('mail');
const emailError = document.querySelector('#mail + span.errorkontakt');
const navn = document.getElementById('navn');
const navnError = document.querySelector('#navn + span.errorkontakt');
const telefon = document.getElementById('telefon');
const telefonError = document.querySelector('#telefon + span.errorkontakt')
const message = document.getElementById('message');
const messageError = document.querySelector('#message + span.errorkontakt')
const navnboks = document.querySelector('.navnboks')
const teleboks = document.querySelector('.teleboks')
const mailboks = document.querySelector('.mailboks')
const messageboks = document.querySelector('.messageboks')
const vernboks = document.querySelector('.vernboks')
const personvern = document.getElementById('checkbox');
const personvernError = document.querySelector('#checkbox + span.errorkontakt')
const submitbtn = document.getElementById('submitbtn');
// THIS DIV WILL CONTAIN ERROR MESSAGES
const errOutput = document.querySelector('.errorsOutput')
email.addEventListener('input', function (event) {
if (email.validity.valid) {
mailboks.setAttribute("class", "data-validation-error-ok" )
emailError.innerHTML = '';
emailError.className = 'errorkontakt';
} else {
showError();
}
});
navn.addEventListener('input', function (event) {
if (navn.validity.valid) {
navnError.innerHTML = '';
navnError.className = 'errorkontakt';
navnboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
telefon.addEventListener('input', function (event) {
if (telefon.validity.valid) {
telefonError.innerHTML = '';
telefonError.className = 'errorkontakt';
teleboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
message.addEventListener('input', function (event) {
if (message.validity.valid) {
messageboks.setAttribute("class", "data-validation-error-ok" )
messageError.innerHTML = '';
messageError.className = 'errorkontakt';
} else {
showError();
}
})
personvern.addEventListener('change', function (event) {
if (personvern.checked == true) {
vernboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
function makeRed() {
if (!navn.validity.valid) {
navnboks.setAttribute("class", "data-validation-error-true")
}
if (!email.validity.valid) {
mailboks.setAttribute("class", "data-validation-error-true")
}
if (!telefon.validity.valid) {
teleboks.setAttribute("class", "data-validation-error-true")
}
if (!message.validity.valid) {
messageboks.setAttribute("class", "data-validation-error-true")
}
if (!personvern.checked == true) {
vernboks.setAttribute("class", "data-validation-error-true")
}
};
function divFill() {
if (navnError.textContent != '') {
errOutput.innerHTML += '<li>Navn</li>'
}
if (emailError.textContent != '') {
errOutput.innerHTML += '<li>E-mail</li>'
}
if (telefonError.textContent != '') {
errOutput.innerHTML += '<li>Telefonnummer</li>'
}
if (messageError.textContent != '') {
errOutput.innerHTML += '<li>Beskjed</li>'
}
}
function showError() {
errOutput.innerHTML = ''
if(navn.validity.valueMissing) {
navnError.textContent = '* Du må fylle inn navnet ditt';
navnError.setAttribute("class", "data-validation-error-true" )
} else if(navn.validity.tooShort) {
navnError.textContent = '* Du må fylle inn hele navnet ditt'
}
if(email.validity.valueMissing) {
emailError.setAttribute("class", "data-validation-error-true" )
emailError.textContent = '* Vennligst fyll inn e-posten din';
} else if(email.validity.typeMismatch) {
emailError.textContent = '* Dette er ikke en gyldig e-postadresse.';
} else if(email.validity.tooShort) {
emailError.textContent = `* Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }.`;
}
if(telefon.validity.valueMissing) {
telefonError.textContent = '* Du må fylle inn telefonnummeret ditt'
telefonError.setAttribute("class", "data-validation-error-true" )
} else if(telefon.validity.tooShort) {
telefonError.textContent = '* Du mangler ett eller flere tall. Vennligst dobbeltsjekk.'
}
if(message.validity.valueMissing) {
messageError.setAttribute("class", "data-validation-error-true" )
messageError.textContent = '* Beskjeden mangler, vennligst fyll inn'
} else if(message.validity.tooShort) {
messageError.textContent = `* Beskjed må være minst ${ message.minLength } tegn.`;
}
}
emailError.className = 'errorkontakt kontaktactive';
navnError.className = 'errorkontakt kontaktactive';
telefonError.className = 'errorkontakt kontaktactive';
messageError.className ='errorkontakt kontaktactive';
console.log(form)
form.addEventListener('submit', function(event) {
if (!navn.validity.valid || !email.validity.valid || !telefon.validity.valid || !message.validity.valid) {
makeRed();
divFill();
event.preventDefault();
console.log('Runs')
}})
<div id="contact-form-wrapper" class="align-right-50 lazyload">
<div id="contact-form-padding">
<h2>Send oss en melding</h2>
<p><span class="required">*</span> obligatorisk felt som du må fylle ut</p><br>
<div class="errorsOutput">
</div>
<div class="skjema">
<form id="kontaktskjema" action="nyhandler.kontakt.php" method="post" novalidate>
<input type="hidden" id="sendtfra" name="Sidetittel" value="{title}" />
<input type="hidden" id="sendtfraURL" name="Side URL" value="{url}" />
<div class="navnboks">
<p>
<label for="navn">
<span>* Navn:</span>
<input type="text" id="navn" name="navn" required minlength="3" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="mailboks">
<p>
<label for="mail">
<span>* E-post:</span>
<input type="email" id="mail" name="mail" required minlength="6" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="teleboks">
<p>
<label for="telefon">
<span>* Telefonnummer:</span>
<input type="tel" id="telefon" name="telefon" required minlength="8" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="messageboks">
<p>
<label for="message">
<span>* Melding:</span>
<input type="text" id="message" name="message" required minlength="10" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="vernboks">
<input type="hidden" id="recapta" name="g-recaptcha-response" />
<p>
<label for="personvern">
<div class="personvern">
<span>* Personvern:</span>
<br>
<input type="checkbox" id="checkbox" name="checkbox" required>
<span>Jeg har lest og godkjent Personvernserklæringen (åpnes i nytt vindu)</span>
<span class="errorkontakt" aria-live="polite"></span>
</div>
</label>
</p>
</div>
<button type="submit" value="Send" class="button-send">Send</button>
</form>
</div>
</div>
</div>
<div class="clear"></div>
</div>
I know it's weirdly specific, and i'll probably clean it up after i get it to work. Right now the validation completes, and runs the functions makeRed() and divFill(), both functions are there to help with accessability issues when not valid, but the form still submits and goes to the handler php.
Thanks.
getElementsByTagName
will return the form tag's value in [0]th location.
So you might need to change your first line of your javascript code as :
const form = document.getElementsByTagName('form')[0];
It will work .
I have an HTML form which is submitted via JavaScript function. It works as expected when submitting on full-screen windows, however, when submitting in a smaller window, such as a smartphone or simply a minimized window on a computer, it doesn't do anything other than quitting the form.
I tried checking by adding a console log when clicking, but nothing is logged when browsing from a smaller display. Below is the code that make up the form.
HTML
<form id="volunteer-form">
<div class="firstNameTF">
<label>First Name</label>
<div>
<input type="text" id="First Name" name="First Name" placeholder="Your first name"/>
</div>
</div>
<br>
<div class="lastNameTF">
<label>Last Name</label>
<div>
<input type="text" id="Last Name" name="Last Name" placeholder="Your last name"/>
</div>
</div>
<br>
<div class="facultyTF">
<label>Faculty</label>
<div>
<input type="text" id="Faculty" name="Faculty" placeholder="Your faculty"/>
</div>
</div>
<br>
<div class="YearDropdown">
<label>Year</label>
<div>
<select id="Year" name="Year">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
<option value="Postgraduate">Postgraduate</option>
<option value="Other">Other</option>
</select>
</div>
</div>
<br>
<div class="AffiliationTF">
<label>Affiliation</label>
<div>
<input type="text" id="Campus Affiliation" name="Campus Affiliation" placeholder="Your student affiliation/involvement"/>
</div>
</div>
<div class="EmailTF">
<label>E-mail Address</label>
<div>
<input type="text" id="Email Address" name="Email Address" placeholder="Your e-mail address"/>
</div>
</div>
<br>
<div>
<button type="submit"id="submit-form">Submit</button>
</div>
</form>
JavaScript
// Check if text fields are complete
$('#submit-form').on('click', function (e) {
console.log("clicked subimt");
e.preventDefault();
var empt = document.forms["volunteer-form"]["First Name"].value;
var empt1 = document.forms["volunteer-form"]["Last Name"].value;
var empt2 = document.forms["volunteer-form"]["Faculty"].value;
var empt3 = document.forms["volunteer-form"]["Campus Affiliation"].value;
var empt4 = document.forms["volunteer-form"]["Email Address"].value;
var c = 0;
var close = document.getElementsByClassName("closebtn");
var i;
if (empt == "" || empt1 == "" || empt2 == "" || empt3 == "" || empt4 == "") {
console.log('form failure')
// window.alert('All fields are required')
// Show error alert
console.log("pop errorAlert");
if (c == 0) {
document.getElementById("errorAlert").style.display = "block";
document.getElementById("errorAlert").style.opacity = "1";
c = 1;
} else {
document.getElementById("errorAlert").style.display = "none";
document.getElementById("errorAlert").style.opacity = "0";
}
} else {
var $form = $('form#volunteer-form'),
url = 'FORM_URL'
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serialize()
}).done(
console.log("success"),
document.getElementById("volunteer-form").reset(),
// window.alert("Thank you for joining me in this campaign! We'll be in touch soon!")
// Show success alert
function pop() {
if (c == 0) {
document.getElementById("successAlert").style.display = "block";
document.getElementById("successAlert").style.opacity = "1";
c = 1;
} else {
document.getElementById("successAlert").style.display = "none";
document.getElementById("successAlert").style.opacity = "0";
}
})
}
// Loop through all close buttons
for (i = 0; i < close.length; i++) {
// When someone clicks on a close button
close[i].onclick = function () {
// Get the parent of <span class="closebtn"> (<div class="alert">)
var div = this.parentElement;
// Set the opacity of div to 0 (transparent)
// div.style.opacity = "0";
// div.style.display = "none";
$(div).css({
"opacity": "0",
"display": "none"
})
// Hide the div after 600ms (the same amount of milliseconds it takes to fade out)
setTimeout(function () {
div.style.display = "none";
}, 600);
}
}
})
This is my javascript function.
function shortCutValidation() {
//var txtObjList = document.getElementsByTagName("input");
//for (var i = 0; i < txtObjList.length; i++) {
// if (txtObjList[i].getAttribute("type") == "text" && this.value != "") {
// // success for i+1 textbox
// }
// else {
// $(txtObjList).closest(".errortext").css("display", "block");
// }
//}
var data = document.getElementsByClassName("w-input");
if (data.length > 0) {
console.log("yes you are in");
for (var i = 0; i < data.length; i++) {
var myvalue = document.getElementsByClassName("w-input");
if (myvalue[i].value == '') {
console.log("yes value is empty"+myvalue[i].value);
$(myvalue[i]).next(".errortext").css("display", "block");
}
else {
console.log("thats ok");
$(data[i]).next(".errortext").css("display", "none");
}
console.log(i);
}
}
}
This is my html code.
<div class="myformgrp w-clearfix w-col">
<div class="w-col w-col-2 w-col-medium-3 w-col-small-12">
<label for="firstname" class="verticle-centerinline">First Name </label>
</div>
<div class="w-col w-col-10 w-col-medium-9 w-col-small-12">
<input type="hidden" id="id" name="id" value="" />
<input type="text" class="w-input" name="fname" id="fname" />
<div class="errortext" style="display:none">required field</div>
</div>
</div>
<div class="myformgrp w-clearfix w-col">
<div class="w-col w-col-2 w-col-medium-3 w-col-small-12">
<label for="firstname" class="verticle-centerinline">Last Name </label>
</div>
<div class="w-col w-col-10 w-col-medium-9 w-col-small-12">
<input type="text" class="w-input" name="lname" id="lname" /><br />
<div class="errortext" style="display:none">required field</div>
</div>
</div>
The problem is that I can't validate all the text box at once
but my for loop is working as expected.
I use jQuery to call the shortCutValidation function.
All I want is when my blur event is called to validate all the text box at once and the error massage should be displayed.
Try This
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validatePet(contact.pet);
reason += validateNumber(contact.number);
reason += validateDisclaimer(contact.disclaimer);
if (reason.length > 0) {
return false;
} else {
return false;
}
}
// validate required fields
function validateName(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Red';
document.getElementById('name-error').innerHTML = "The required field has not been filled in";
var error = "1";
} else {
name.style.background = 'White';
document.getElementById('name-error').innerHTML = '';
}
return error;
}
// validate email as required field and format
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter an email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Red';
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
email.style.background = 'White';
document.getElementById('email-error').innerHTML = '';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter a phone number";
phone.style.background = 'Red';
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
phone.style.background = 'Red';
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
phone.style.background = 'Red';
} else {
phone.style.background = 'White';
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
function validatePet(pet) {
if ((contact.pet[0].checked == false) && (contact.pet[1].checked == false) && (contact.pet[2].checked == false)) {
document.getElementById('pet-error').innerHTML = "Pet required";
var error = "2";
} else {
document.getElementById('pet-error').innerHTML = '';
}
return error;
}
function validateNumber(number) {
var num = document.forms["contact"]["number"];
var y = num.value;
if (!isNaN(y)) {
//alert('va');
if (y < 0 || y > 50) {
//Wrong
number.style.background = 'Red';
document.getElementById("number-error").innerHTML = "Must be between 0 and 50.";
var error = "10";
} else {
//Correct
number.style.background = 'White';
document.getElementById("number-error").innerHTML = "";
}
return error;
} else {
document.getElementById("number-error").innerHTML = "Must be a number.";
var error = "3";
}
return error;
}
function validateDisclaimer(disclaimer) {
var error = "";
if (document.getElementById("disclaimer").checked === false) {
document.getElementById('disclaimer-error').innerHTML = "Required";
var error = "4";
} else {
document.getElementById('disclaimer-error').innerHTML = '';
}
return error;
}
.error {
color: #990000;
}
input::-webkit-input-placeholder {
color: white !important;
}
input:-moz-placeholder { /* Firefox 18- */
color: white !important;
}
input::-moz-placeholder { /* Firefox 19+ */
color: white !important;
}
input:-ms-input-placeholder {
color: white !important;
}
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<div>
<label>First Name</label>
<input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<div>
<label>Nickname</label>
<input placeholder="Nickname" type="text" name="nickname" id="nickname" tabindex="2" autofocus />
</div>
<div>
<label>Email</label>
<input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
<div id="email-error" class="error"></div>
</div>
<div>
<label>Phone</label>
<input placeholder="Phone" type="tel" name="phone" id="phone" tabindex="4" autofocus />
<div id="phone-error" class="error"></div>
</div>
<div>
<label>I prefer</label>
<input type="radio" name="pet" id="Dogs" tabindex="5" autofocus />Dogs
<input type="radio" name="pet" id="Cats" tabindex="6" autofocus />Cats
<input type="radio" name="pet" id="Neither" tabindex="7" autofocus />Neither
<div id="pet-error" class="error"></div>
</div>
<div>
<label>My favorite number between 1 and 50</label>
<input placeholder="Favorite number between 1 and 50" type="text" name="number" id="number" tabindex="8" autofocus />
<div id="number-error" class="error"></div>
</div>
<div>
<label>Disclaimer</label>
<input type="checkbox" name="disclaimer" id="disclaimer" tabindex="9" autofocus />I confirm that all the above information is true.
<div id="disclaimer-error" class="error"></div>
</div>
<div>
<button type="submit" name="submit" id="submit" tabindex="10">Send</button>
</div>
</form>
Happy Coding
I have a problem with innerHTML
I'm trying to replace all child elements of a div (wipe it out) and replace with a text. Just to give you idea, this is a registration form, after clicking submit, it should clear the form and output some text. It looks like it doesn't take any affect on the div that I am targeting
here is the function
function signup() {
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if (u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "") {
status.innerHTML = "Fill out all of the form data";
} else if (p1 != p2) {
status.innerHTML = "Your password fields do not match";
} else if (_("terms").style.display == "none") {
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText.trim() != "signup_success") {
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
_("signupform").innerHTML = "OK " + u + ", check your email inbox and junk mail box at <u>" + e + "</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u=" + u + "&e=" + e + "&p=" + p1 + "&c=" + c + "&g=" + g);
}
and here is the form:
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once( "php_includes/template_country_list.php"); ?>
</select>
<div>
<br>
<br>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<br>
<br>
<h3>Please read the Terms and Conditions (opens a new window)</h3>
<a href="iLOVEiTtermsandCONS.pdf" title="Terms and Conditions" target="_blank">
<p>Terms and Conditions</p>
</a>
</div>
<br />
<br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
any ideas what could be wrong? I'm not good with java script at all
Thanks in advance.
I don't know what does _(" ").value mean. But if you change this style to document.getElementByid(" "), it works.
I'm having an issue when trying to submit my form. I have made a workaround so that the input gets sent to parse.com by using a hidden button which is visible until all fields are filled in, then this button is hidden and the real submit button is enabled. The problem is that I want to be able to submit the form directly by clicking the submit button without having to click the button twice. I have the following HTML:
<form id="vcardForm" method="post" >
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
<p>
<input type="text" id="telefon" name="telefon" onclick="getFullemail()" />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
<button type="button" id="submitKnop" onclick="validateForm()" ></button>
Javascript:
<script type="text/javascript">
function getFullemail() {
document.getElementById('fullemail').value =
document.getElementById('email1').value + '#' +
document.getElementById('email2').value;
}
</script>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name == '' || vorname == '' || email == '' || firma == '' || telefon == '' ) {
alert('Bitte alle Felder ausfüllen. Danke.');
e.preventDefault();
}else {
document.getElementById('submitKnop').style.visibility = 'hidden';
document.getElementById('submitBtn').disabled = false;
}
}
</script>
<script>
function functions() {
sendTheMail();
}
</script>
Parse.com script
$(document).ready(function() {
var parseAPPID = "bla";
var parseJSID = "bla";
Parse.initialize(parseAPPID, parseJSID);
var VcardObject = Parse.Object.extend("VcardObject");
$("#vcardForm").on("submit", function(e) {
e.preventDefault();
console.log("Handling the submit");
//add error handling here
//gather the form data
var data = {};
data.name = $("#name").val();
data.vorname = $("#vorname").val();
data.fullemail = $("#fullemail").val();
data.telefon = $("#telefon").val();
data.firma = $("#firma").val();
var vcard = new VcardObject();
vcard.save(data, {
success:function() {
openPage('danke');
console.log("Success");
},
error:function(e) {
console.dir(e);
}
});
});
});
If i understand you correctly, you'd like to click button after form is filed and if all fields are valid the form should be send. If so you need to do following changes:
1) remove from html
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
2) change your validateForm - replace this lines
document.getElementById('submitKnop').style.visibility = 'hidden';
document.getElementById('submitBtn').disabled = false;
with
functions()
It will spare your from using two buttons.When submit button is clicked check if all the fields are filled in or not.Use && operator instead of || operator.Because you want all the fields to be filled
if(name != '' && vorname != '' && email != '' && firma != '' && telefon != '' )
If all fields are filled it will alert a message which will tell you that your form is submitted.Otherwise it will alert you to fill all the fields
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name != '' && vorname != '' && email != '' && firma != '' && telefon != '' ) {
alert('form is sumbitted.');
e.preventDefault();
}else {
alert('fill all fields !!');
}
}
<form id="vcardForm" method="post" >
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
<p>
<input type="text" id="telefon" name="telefon" onclick="getFullemail()" />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="validateForm()" value=" submit " >
modify validateForm
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name == '' || vorname == '' || email == '' || firma == '' || telefon == '' ) {
alert('Bitte alle Felder ausfüllen. Danke.');
return false
}
return true
}
and replace
console.log("Handling the submit");
//add error handling here
//gather the form data
with
if(!validateForm()) return
sendTheMail(...al your params here)
and the last step replace in your html
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
<button type="button" id="submitKnop" onclick="validateForm()" ></button>
with
<input type="submit" id="submitBtn" value=" ">