On my pages I need to have a varying amount of forms that all have to have Google reCaptcha on them.
I have a function that renders out the forms, which I call via , etc.
I then loop through the form elements on my page in javascript and generate an event listener for each submit on each form, this works fine.
Once grecaptcha.execute() has run it's then looking for the 'data-callback' attribute to find the function to submit the form.
My problem is that I can't find a way to loop through each form and generate the data-callback function programatically.
I have tried to write a for loop that generates the data-callback function, but I cannot work it out.
I have tried making an object with some variables, but cannot connect the dots:
var formSubmitObj = {
formSubmit0: function() { document.getElementById('formSubmit-0').submit(); },
formSubmit1: function() { document.getElementById('formSubmit-1').submit(); },
formSubmit2: function() { document.getElementById('formSubmit-2').submit(); }
};
let formNo = 2;
formSubmitObj['formSubmit' + formNo]();
<form action="mailer.php" method="post" id="myForm-<?php echo $position ?>">
<div class="g-recaptcha"
data-sitekey="xxxxxxxx"
data-size="invisible"
data-callback="formSubmit-<?php echo $position ?>">
</div>
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="email">Email</label>
<input type="text" name="email" required>
<button type="submit">submit form <?php echo $position ?></button>
</form>
function form($position){
include ('form.php');
}
const forms = document.querySelectorAll('form');
for (let i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function() {
event.preventDefault();
grecaptcha.reset();
grecaptcha.execute();
});
}