Google captcha v3 button twice click is need to complete action - javascript

I just installed recaptcha v3 on a form and I found that the submit button needs to be clicked 2x to make it work.First submit it will get the captcha validation. After the second click it will pass redirect.
Html code
<div class="form_wrpr">
<f:form.hidden id="g-recaptcha-response" property="g-recaptcha-response" />
<button class="g-recaptcha btn btn-blue" id="reg-submit"
data-sitekey="{fields.clientKey}" data-callback='onSubmit' data-action='submit' type= "submit">
{fields.Button}</button>
</div>
Script
$("#reg-submit").on('click', function(){if($('#company').val() == '') {
$('#company_error').text($('#company_error').data("error-mandatory"));
isvalid4 = false;
} if(!isvalid4) {
return false; }
if (grecaptcha.getResponse().length != 0) {
$("#reg-submit").attr("disabled", true);
$.ajax({
type: 'POST',
url: $('#form-ajaxurl').val(),
data: $('#demo_form').serialize(),
success: function(data){
$('#reg-submit').attr("disabled", false);
var output = JSON.parse(data);
if(output.error == 1) {
$('#form-errors').html(output.result);
}
else if(output.error == 2){
$('#form-errors').html(output.result);
} else {
window.location.href = 'test.com'+output.result;
} } }); }else { var elementClicked = 0;
$(".g-recaptcha").on('click', function(){
elementClicked = 1; if( elementClicked == 1)
{ $('#g_captchaerror').text(''); } }); if(elementClicked == 0)
{ isvalid4 = false;
$('#g_captchaerror').text($('#g_captchaerror').data("error-mandatory"));
} } });

The code creates a button that a user must click on in order to complete the CAPTCHA challenge. When the button is clicked, the grecaptcha.execute() function is called, which will trigger the reCAPTCHA v3 verification process.
$(document).ready(function() {
var alreadySubmitted = false;//adding a extra variable to check already submitted.
$("#reg-submit").on('click', function(){
if(!isvalid4) {
return false;
}
grecaptcha.ready(function() {
grecaptcha.execute('clientkey', {
action: 'submit'
}).then(function(token) {
$.ajax({
type: 'POST',
url: $('#form-ajaxurl').val(),
data: $('#demo_form').serialize(),
success: function(data){
// $('#reg-submit').attr("disabled", false);
var output = JSON.parse(data);
if (output.error == 1) {
$('#form-errors').html(output.result);
} else if(output.error == 2) {
$('#form-errors').html(output.result);
} else {
window.location.href = 'test.com'+output.result;
}
}
});
});
});
});

Related

Search by pressing Enter

I would like, that when the Enter button is pressed, the application will search a city, the action now is started by pressing the Search button. Below is my code:
const ENTER_KEY_CODE = 13;
document.querySelector('#city').addEventListener('keyup', function(e) {
if (e.keyCode === ENTER_KEY_CODE) {
var city = $(this).val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
});
} else {
$("error").html('Field cant be empty')
}
};
});
All you need to do is add a keyup events listener to your input element. When the handler is called, simply check the e.keyCode to see if it's enter was pressed. If it was, do your thing:
const ENTER_KEY_CODE = 13;
document.querySelector('#textEl').addEventListener('keyup', function(e) {
if (e.keyCode === ENTER_KEY_CODE) {
var city = $(this).val();
var url = `http://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&units=metric&APPID=bb037310921af67f24ba53f2bad48b1d`;
if (city !== '') {
console.log(`Make ajax call to ${url}`);
//Make your AJAX call here
} else {
console.log('City cannot be blank!');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="textEl" type="text" />
<div id="error"></div>
This a sample code please use this a reference code.
HTML code
<input id="InputEnter" >
Javascript code
var input = document.getElementById("InputEnter");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
$(document).ready(function () {
$('#submitWeather').click(function () {
var city = $("#city").val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
}
});
This should work. I assume that your ajax request is correct.
document.querySelector('#submitWeather').addEventListener('keypress', function(e){
if(e.which === 13){
// your ajax request
}
})

.submit() function not working in jquery

I am facing on problem my submit function not working I don't know where is the problem. I am using laravel framework 5.2 h
$('#CheckImageCount').on('click', function() {
var arr = [];
$('.table-error').find('tr').each(function() {
if ($(this).find('td:eq(1)').find('select').val() != '') {
if ($(this).find('td:eq(2)').find('select').val() == '') {
arr.push('false');
} else {
arr.push('true');
}
} else {
arr.push('true');
}
});
if ($.inArray('false', arr) > -1) {
swal("Alert!", "Please Select Working Hours in right way!")
return false;
} else {
$.ajax({
type: 'POST',
url: 'CheckImageCount',
success: function(resp) {
if ($.trim(resp) == "empty") {
$('.error-1').fadeIn('fast').delay(1000).fadeOut('fast');
return false;
} else {
$("#registerBusiness").submit(); // here i want to submit the form
}
},
error: function() {}
});
}
});
My form id is registerBusiness it not submit the form even my page not
goto that function here is my form and submit button
<form id="registerBusiness" role="form" method="POST" action="{{ url('/business-for-sale' )}}">{{ csrf_field() }}
And Submit buttton
<button id="CheckImageCount" type="button" class="btn btn-info">Save And Continue </button>

Contact form submitting twice

I added a pop up form for email subscription and it is sending twice on submission and the confirmation message is also being displayed twice
Here is the code:
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function(e) {
e.preventDefault();
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(mailvalid == true) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! You have signed up for a trial. A member of our team wil soon be in contact :)</strong></p>");
setTimeout("$.fancybox.close()", 1700);
});
}
}
});
}
});
});
I don't think there's any need to write this line:
$("#contact").submit(function() { return false; }); // Remove this
You can remove this line:
$("#send").on("click", function(){ // Remove this
And write this instead:
$("#contact").submit(function(e) { // Add this
e.preventDefault(); // Add this
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
/* Other code */
});

Validating individual form inputs with javascript

I have a registration form that validates a text field, if it's empty when a user clicks/tabs off which shows an error message. My issue with the below code is its a lot to duplicate across several form fields. The below example is for first name but I can't see a way of using what I have to do the same for more than one field.
/* this will call ajax call after entering all the below three fiels */
var $fields = $('#testid');
$fields.live('blur',function(e) {
e.preventDefault();
var $emptyFields = $fields.filter(function() {
return $.trim(this.value) === "";
});
if ($emptyFields.length) {
var frm = $(this).parents('form');
var url=$('#valNameEmail').val();
jQuery.ajax({
url: url,
data: $(this).parents('form').serialize(),
type: 'POST',
dataType: "json",
success: function(response){
if (response.HtmlMessage === 'success'){
$('.reg-alreadyRegistered').html('');
$('.reg-alreadyRegistered').css('display', 'none');
ACC.registration.tickIcon($('#testid'));
var radioExCustValue = $('#registration-form input[name=existingCustomer]:checked').val();
if (userNameAjax === true) {
if (radioExCustValue == 'false'){
$('#regFormSubmit').removeAttr('disabled');
}
else {
if (customerValidation == true){
$('#regFormSubmit').removeAttr('disabled');
}
}
}
emailIDajax = true;
} else {
ACC.registration.errorIcon($('#testid'));
$('.reg-alreadyRegistered').html(response.HtmlMessage);
$('.reg-alreadyRegistered').css('display', 'block');
emailIDajax = false;
$('#regFormSubmit').attr('disabled','disabled');
}
},
error: function(){
//alert(response);
//console.log('ERROR!')
}
});
}
});
You can give the same inputs that require same sort of validation a class (or if you want it for example for all input[type=text] then you can use it for the selector.
So let's say I have a form like this:
<form id="mform">
<input type="text" class="inptxt" name="it1" />
<input type="text" class="inptxt" name="it2" />
<!-- other similar text inputs with the same class -->
<input type="submit" id="sub" value="Submit" />
</form>
I have a function for text inputs which returns false if the field is empty, otherwise true:
$.fn.isValid = function() {
return $.trim($(this).val());
}
And then I get the inputs by class and validate them all at once:
$('#mform').on('submit', function(e) {
e.preventDefault();
var allValid = true;
$('.inptxt').each(function() {
if (!$(this).isValid()) {
$(this).css('background-color', 'red');
allValid = false;
}
else
$(this).css('background-color', 'white');
});
if(allValid) {
//everything's valid ... submit the form
}
});
jsfiddle DEMO
This worked for me:
$('#registration-form input').blur(function(){
if( $(this).val().length === 0 ) {
ACC.registration.errorIcon($(this));
}
else{
ACC.registration.tickIcon($(this));
}
});
thanks for your help

Is there a way to prevent submitting a form with this javascript/jquery?

I have searched the net, i´ve tried implementing "preventdefaults" and "return false" statements all over the place, but I can´t seem to find a way to prevent this form submitting and reloading the page. It only reloads when the form has been validated. I´m kind of a beginner, but I really tried hard achieving the script to validate a form (which has "post"-method and "#" as action), and make an ajax-call. It´s a school assignment and would be graceful towards any pointers you guys could give.
$(document).ready(function()
{
$("#submit").click(function()
{
var gbname = $("#gbname")[0];
var gbmessage = $("#gbmessage")[0];
formFields = [gbname, gbmessage]
var warning = false;
for (i=0; i<formFields.length; i++)
{
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "")
{
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true)
{
alert("Vänligen fyll i fälten korrekt!");
return false;
}
else
{
$.post('ajax.php', {gbname: gbname, gbmessage: gbmessage},
function(data)
{
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" +gbname+ "</p> <p class='messages'><b>Meddelande:</b>" +gbmessage+ "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
});
return false;
}
return false;
});
});
Your references to the input elements as objects and the data returned from your AJAX call were a bit muddled.
Also incorporated the suggestion of binding to the form's submit event. DEMO
$(document).ready(function () {
function clearForm(){
$('input.reset').each(function(){
$(this).val('');
});
}
$("form").on('submit', function () {
alert('submitted!');
var gbname = $("#gbname");
var gbmessage = $("#gbmessage");
formFields = [gbname[0], gbmessage[0]]
var warning = false;
for (i = 0; i < formFields.length; i++) {
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "") {
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true) {
alert("Vänligen fyll i fälten korrekt!");
return false;
} else {
var J = JSON.stringify({
"gbname": gbname.val(),
"gbmessage": gbmessage.val()
});
console.log(J);
$.ajax({
type: "POST",
url: '/echo/json/',
datatype: 'json',
data: {
json: J,
delay: 3
},
success: function (data) {
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" + data.gbname + "</p> <p class='messages'><b>Meddelande:</b>" + data.gbmessage + "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
} // end success
}); // end ajax
return false;
} // end else
return false;
});
});
I suggest using
$("form").on('submit', function (e) {
[...]
if(validationErrors) {
alert(Errormessage);
e.preventDefault();
}
[...]
instead of returning false.
https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
In order to get it to work, you have to use the event as a parameter of your callback function.

Categories

Resources