Having Trouble Making Google recaptcha reequired in HTML form - javascript

It seems that this script is working and stopping the submit button from working until after the captcha v2 has been verified.
I tried following some guides from previous questions but nothing seems to work for me.
Could someone shed some light on me? Thanks.
<form id="myForm" class="contact-form" action="php/send-email.php" method="post" novalidate>
<div class="row">
<div class="column width-6">
<input type="text" name="fname" class="form-fname form-element large" placeholder="First Name*" tabindex="1" required>
</div>
<div class="column width-6">
<input type="text" name="lname" class="form-lname form-element large" placeholder="Last Name" tabindex="2">
</div>
<div class="column width-6">
<input type="email" name="email" class="form-email form-element large" placeholder="Email address*" tabindex="3" required>
</div>
<div class="column width-6">
<div class="field-wrapper">
<div class="form-select form-element">
<select name="budget" tabindex="4" class="form-aux" data-label="Project Type">
<option selected="selected" value="">Project Type</option>
<option value="">Website Project</option>
<option value="">Marketing</option>
<option value="">Branding</option>
<option value="">Other</option>
</select>
</div>
</div>
</div>
<div class="column width-6">
<input type="text" name="honeypot" class="form-honeypot form-element large">
</div>
</div>
<div class="row">
<div class="column width-12">
<div class="field-wrapper">
<textarea name="message" class="form-message form-element large" placeholder="Message(Include phone number if needed)*" tabindex="7" required></textarea>
</div>
</div>
<div class="column width-12">
<div class="g-recaptcha"
data-callback="onCompleted"
data-sitekey="6Legq1IUAAAAANF4DoxqEkVyS3jY0N4UQKDUPuBa">
</div>
<input type="submit" value="Send Email" class="form-submit button medium bkg-theme bkg-hover-theme color-white color-hover-white" onsubmit="check_if_capcha_is_filled">
</div>
</div>
</form>
<script>
$('#myForm').submit(function(event) {
console.log('form submitted.');
if (!grecaptcha.getResponse()) {
console.log('captcha not yet completed.');
event.preventDefault(); //prevent form submit
grecaptcha.execute();
} else {
console.log('form really submitted.');
}
});
onCompleted = function() {
console.log('captcha completed.');
$('#myForm').submit();
alert('wait to check for "captcha completed" in the console.');
}
Yes the stript is closed I don't know why the end tag isn't showing.

Related

Bootstrap validation with JavaScript - disable submission with invalid fields

I have the following HTML code:
<form class="row g-3 needs-validation" novalidate>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">First name</label>
<input type="text" class="form-control" id="validationCustom01" value="Mark" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4">
<label for="validationCustom02" class="form-label">Last name</label>
<input type="text" class="form-control" id="validationCustom02" value="Otto" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4">
<label for="validationCustomUsername" class="form-label">Username</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend">#</span>
<input type="text" class="form-control" id="validationCustomUsername" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
<div class="col-md-6">
<label for="validationCustom03" class="form-label">City</label>
<input type="text" class="form-control" id="validationCustom03" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3">
<label for="validationCustom04" class="form-label">State</label>
<select class="form-select" id="validationCustom04" required>
<option selected disabled value="">Choose...</option>
<option>...</option>
</select>
<div class="invalid-feedback">
Please select a valid state.
</div>
</div>
<div class="col-md-3">
<label for="validationCustom05" class="form-label">Zip</label>
<input type="text" class="form-control" id="validationCustom05" required>
<div class="invalid-feedback">
Please provide a valid zip.
</div>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
Agree to terms and conditions
</label>
<div class="invalid-feedback">
You must agree before submitting.
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</form>
With the following JavaScript code, to validate the user input. If there are any invalid fields, it should the user stop submitting his request:
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
// putting alert here does not work..?
// something like alert('successfully validated your request!')
}, false)
})
})()
The problem is: I want to alert the user, if the submission was successfully, with the alert() function. But I can't figure out where to put the alert function. I marked the code where I tried putting the alert function into, but it's always triggering even when it's not even validated. Does somebody know what am I doing wrong here? Thank you very much.

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

Clear input fields on submit

I am trying to clear my input fields after the user clicks on submit with MailChimp, although I seem to be having problems with it.
I have tried a lot of options to make it work and nothing does the trick. Can you help me?
Thanks, in advance.
HTML
<div class="mc-field-group">
<div class="row">
<div class="col-sm-6 col-md-6">
<input type="text" placeholder="Type your name here..."
value=""
name="NOME" class="form-control input-box required pull-
right" id="mce-NOME">
</div>
<div class="col-sm-6 col-md-6">
<input type="text" placeholder="Type your email here..."
value="" name="EMAIL" class="form-control input-box
required pull-left" id="mce-EMAIL">
</div>
</div>
</div>
<div class="mc-field-group">
<div class="row">
<div class="col-sm-12">
<textarea limit="1000" placeholder="Type your message here..."
style="height: 100px; width: 500px;" value=""
name="MENSAGEM" class="form-control textarea-box required"
id="mce-MENSAGEM">
</textarea>
</div>
</div>
</div>
JS
$('#mc-embedded-subscribe-form').ajaxChimp({
callback: mailchimpCallback,
url: ""
});
function mailchimpCallback(resp) {
if (resp.result === 'success') {
$('.subscription-success').html('<span class="icon_check_alt2"></span>' + ' Agradecemos por sua mensagem.<br />Entraremos em contato em breve.').fadeIn(1000);
$('.subscription-error').fadeOut(500);
} else if(resp.result === 'error') {
$('.subscription-error').html('<span class="icon_close_alt2"></span>' + 'Oops... Houve um erro ao tentar enviar sua mensagem.<br/>Por favor, tente novamente em alguns minutos.').fadeIn(1000);
}
}
You can use $(':input').val(''); and $('textarea').val('');
$("#reset").click(function(){
$(':input').val('');
$('textarea').val('');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mc-field-group">
<div class="row">
<div class="col-sm-6 col-md-6">
<input type="text" placeholder="Type your name here..."
value=""
name="NOME" class="form-control input-box required pull-
right" id="mce-NOME">
</div>
<div class="col-sm-6 col-md-6">
<input type="text" placeholder="Type your email here..."
value="" name="EMAIL" class="form-control input-box
required pull-left" id="mce-EMAIL">
</div>
</div>
</div>
<div class="mc-field-group">
<div class="row">
<div class="col-sm-12">
<textarea limit="1000" placeholder="Type your message here..."
style="height: 100px; width: 500px;" value=""
name="MENSAGEM" class="form-control textarea-box required"
id="mce-MENSAGEM">
</textarea>
</div>
</div>
</div>
<input type="button" id="reset" value="Reset">
You can simply put it in your success handler, something like
$('.mc-field-group input, .mc-field-group textarea').val('')
should do the trick.
If you have the fields in a form, you can use reset on the form
$('#formId')[0].reset();
$('.mc-field-group').find('input,textarea').val('')

Multiple forms not working in a J2EE web application

I have designed a web page which contains multiple forms and each form is provided with its unique submit button and are directed to different servlets on submission.
But at a time only one is getting submitted successfully to the database and another form is not even getting directed to its servlets.
How to do it?
<!-- UPDATE DONOR CARD-->
<div class="col-xl-4 " style="opacity:0.9;">
<div class="card bg-info text-center card-form mb-4">
<div class="card-body">
<h3 class="align-center">Update Donors Detail</h3>
<p>Please fill out this form to update </p>
<form action="UpdateHospitalController" method="post" name="update">
<div class="form-group">
<input type="text" class="form-control form-control-lg" placeholder="Mobile no." id="mobNo" name="mobNo">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" placeholder="Date" id="datepickers" name="date">
</div>
<input type="submit" class="btn btn-dark btn-block" name="updateSubmit">
</form>
</div>
</div>
</div>
<!-- ADD DONOR CARD-->
<div class="col-xl-4 " style="opacity:0.9;">
<div class="card bg-info text-center card-form mb-4">
<div class="card-body">
<h3 class="align-center">Add Donors</h3>
<p>Please fill out this form to add </p>
<form action="HospitalController" method="post" onclick="return(validate())" name="addForm">
<div class="form-group">
<input type="text" class="form-control form-control-lg" placeholder="Mobile no." maxlength="10" id="mobNo" name="mobNos">
<span id="sp1"></span>
</div>
<div class="form-group" >
<input type="text" class="form-control form-control-lg " placeholder="Name" id="name" name="userName">
<span id="sp2"></span>
</div>
<div class="form-group">
<select class="form-control form-control-lg" placeholder="Blood Group" name="bglist" id="list">
<option value="Opos">O+</option>
<option value="Oneg">O-</option>
<option value="Apos">A+</option>
<option value="Aneg">A-</option>
<option value="Bpos">B+</option>
<option value="Bneg">B-</option>
<option value="ABpos">AB+</option>
<option value="neg">AB-</option>
</select>
<span id="sp3"></span>
</div>
<div class="form-group" >
<input type="text" class="form-control form-control-lg " placeholder="Date" id="datepicker" id="date" name="dates">
<span id="sp4"></span>
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" placeholder="City" id="city" name="city">
<span id="sp5"></span>
</div>
<input type="submit" class="btn btn-dark btn-block" name="addDonor">
</form>
</div>
</div>
</div>
You can only perform one query in database at a time. You need to direct the servlet to this page again using response.sendRedirect("filename") and then try with other form. Hope it helps.If not lemme know.

Alert User field that is blank is required

Problem: I would like to be able to alert the user if a particular field is empty. Here is how the form looks:
When the user enters a zip code and selects search, I would like a pop up to display to alert the user to select a distance and not display the results. If the user enters hospital name and city drop down, I do not want the alert to appear. Only when the zip code is entered and when the search button is selected.
Here is the form:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance">
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
and here is the script that alerts when the miles is blank:
function validateForm() {
var x = document.forms["UrgentCareSearch"]["distance"].value;
if (x == "" || x=="null") {
alert("Please select distance");
return false;
}
UPDATE
I have done the following and it still does not work the way I want to (which is to show the alert when the search button is entered and when the user has entered a zip code. Meaning once the user has entered a zip code and click on the search button to populate the results, the alert will appear notifying to select the miles and the results will not show until user has entered how many miles and click search again):
function validateForm() {
var x = document.forms["UrgentCareSearch"]["miles"].value;
var $zip = $('#zip');
if ((x == "" && $zip != "") ||(x=="null" && $zip != "")) {
alert("Please select distance");
return false;
}
and this is what I when I used required:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return checkTextField()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles" required>
<option value=""></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
adding required to each of the input or select elements would prevent the form from being submitted if they are left blank
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" required /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City" required>
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" required>
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
Or there can jquery touch look at this
first give your form an id lets say myform
$(document).ready(function()
{
$('#myform').submit(function()
{
var name = $("#hospital").val();
var name = $("#city").val();
if(name == "" || name == " ")
{
alert("Please enter name");
return false;
}
if(city == "" || city== " ")
{
alert("Please enter city");
return false;
}
//Just like this and at the end when you are satisfied
$(this).submit();
});
});
From what I understand by your problem statement, you can do the following in your validation function.
function validateForm() {
var miles = document.forms["UrgentCareSearch"]["distance"].value;
var zip = document.forms["UrgentCareSearch"]["zip"].value;
if (zip && !miles) {
event.preventDefault(); // This will prevent the form submit
alert("Please enter the Miles.");
return false; // Does't submit the form (for IE)
}
}
Also, when calling the function, just call the function directly.
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="validateForm();">

Categories

Resources