submit handler working only on second attempt - javascript

I'm using the 1000hz bootstrap validator with my form before Invisible reCaptcha kicks in. To do so, I had to use a jQuery submit handler.
The problem is that the handler works only after the submit button is clicked twice. On the first click, the form is submitted, bypassing the handler and by doing so the invisible reCaptcha does not get executed and, of course, I get an error.
This is the form:
<form role="form" data-toggle="validator" data-disable="true" id="contactform" method="post" action="result.php">
<div class="form-group"><label for="InputName1">Envianos un E-mail</label><input type="text" class="form-control" name="nameofuser" placeholder="Nombre, Apellido" required>
</div>
<div class="form-group"><label for="InputEmail1">Email</label><input type="email" class="form-control" name="email" placeholder="Tu E-mail" required data-error="Porfavor, ingrese una dirección de Email valida.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group"><label for="InputName1">Mensaje</label><textarea class="form-control" rows="5" name="comment" required></textarea>
</div>
<div id='recaptcha' class="g-recaptcha"
data-sitekey="6LfCKjQUAAAAAPSp2YVmv-Yv2sOIPW_gp6CLVBUj"
data-callback="onCompleted"
data-size="invisible">
</div>
<button type="submit" id="submit" style="font-size: 24px;" class="btn btn-box openSans" >Enviar</button>
</form>
And this the JS:
$("#contactform").submit(function(e) {
$('#contactform').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
console.log("FORM INVALIDO");
} else {
// everything looks good!
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.');
$("#contactform").submit();
}
If someone wants to look at the console, here is a page showing the issue:
https://ccromatica.com/contacto

You're defining an event handler inside the submit callback.
The code $('#contactform').validator().on('submit') isn't registered until you first submit the form. The second time you submit the form, the event handler kicks into action and does what it's meant to do.
The simplest solution is to move all event handlers, like the one mentioned above, outside of any submit functions.
Make sure that whenever you're defining an event handler, it's run first, rather than only being defined based on some other condition.

Related

Adding an event listener to a submit button to run a function

Hey guys I'm writing an app with javascript and I'm trying to add an event listener to the submit button which is the "Send Email" button that someone clicks to send an email.
I know the code works for adding the email since when i run it outside of an event listener, it sends the email. So there's an issue with my event listener for some reason.
Currently - nothing happens when I click the send mail button. I get no error it just returns me to the inbox.
I'm sure the event listener isn't working for some reason.
Anyone see what I'm doing wrong? Thanks
html:
<div id="compose-view">
<h3>New Email</h3>
<form id="compose-form"
method="POST">
{% csrf_token %}
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="submit" id="sendEmail" class="btn btn-primary"/>
</form>
</div>
js:
const element = document.getElementById('sendEmail');
element.addEventListener('click', function() {
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: 'card51short#gmail.com',
subject: "buglets",
body: 'Hes a fat one'
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
});
});
}
Its because your form method is post which is going to make a post request when you click the button and the javascript isn't going to run because it is attempting to make a post request to an endpoint that doesn't exist. So you need to remove the html attribute method from the form.

Adding functionality to submit button within validation form - Bootstrap 4

I know this is a simple fix but through multiple google searches, I can't seem to find the answer to my question. I'm using a validation form from bootstrap 4, and I'm just trying to add functionality to my button by simply linking it to a different page. I tried using the anchor tag,
i.e. Submit
which will work, but the obviously validation is bypassed.
so currently I have this button within a form:
<button class="btn btn-primary" type="submit" >Submit form</button>
</form>
with this java script:
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
What needs to be added to the js to make the button functional?? Thank you for any assistance!!
Here's a simplified version, the code is heavily commented.
// wait for page to load then run the code inside
window.onload = () => {
// Select the form we want to validate
let form = document.querySelector('form');
// listen for submit event
form.onsubmit = (event) => {
// prevent the form from posting so the page won't refresh
event.preventDefault();
// debugging log statememnet (not needed)
console.log('Form submitted')
// checking for form validation
if (form.checkValidity() === false) {
// if we're inside this if statement, the form is invalid
// we add the boostrap class to handle styling
form.classList.add('was-validated');
// debugging log statememnet (not needed)
console.log('Form not valid')
} else {
// if we're inside this if statement, the form is valid and ready for further actions
// debugging log statememnet (not needed)
console.log('Form valid')
// redirect to the target page
location.href = "www.example.com"
}
}
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-3">
<label for="validationCustom01">First name</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-3">
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-3">
<label for="validationCustomUsername">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend">#</span>
</div>
<input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
If you're a beginner i suggest you stay away from libraries and just play with vanilla js/css build everything from scratch if you get stuck your research on every single line of code, Then and only then you can start messing with libraries and such.

Prevent angular form from submitting if input is blank

I have an Angular form inside a ng2 popup:
<popup>
Sign up for our Newsletter! <form #f="ngForm" (ngSubmit)="onSubmit()" novalidate>
</button> <input type="email"/>
<button>Submit</button>
</form>
</popup>
<button class="submit" (click)="ClickButton()">Sign up for our Newsletter </button>
here is the onClick event function:
constructor(private popup:Popup) { }
testAlert() { ClickButton(){
alert("Newsletter event works"); this.popup.options = {
widthProsentage: 15,
showButtons: false,
header: "Sign up for our Newsletter!",
}
this.popup.show(this.popup.options);
}
It works fine but I am able to submit her even if the input is blank, how can I make so that it does not submit if it is clicked empty
I tried using RegEx but it did not work
Consider adding validation.
Something like this:
<div class="form-group row">
<label class="col-md-2 col-form-label"
for="userNameId">User Name</label>
<div class="col-md-8">
<input class="form-control"
id="userNameId"
type="text"
placeholder="User Name (required)"
required
(ngModel)="userName"
name="userName"
#userNameVar="ngModel"
[ngClass]="{'is-invalid': (userNameVar.touched || userNameVar.dirty) && !userNameVar.valid }" />
<span class="invalid-feedback">
<span *ngIf="userNameVar.errors?.required">
User name is required.
</span>
</span>
</div>
</div>
You can then disable the submit button if the fields are not valid:
<button class="btn btn-primary"
type="submit"
style="width:80px;margin-right:10px"
[disabled]="!loginForm.valid">
Log In
</button>
(ngSubmit) is built-in event emitter inside of Angular ngForm and is directly related to button element which is kind of a trigger for form submission.
Therefore, as lealceldeiro said, you only need onSubmit function and button intended for submission inside of your form tag.
Please provide live demo so we can see the whole file (.ts particularly).
Setting the validation properly depends on what kind of forms you're going to use (template or ReactiveForms).
See more about proper ngForm usage in official documentation.

Ember.js TextField action submits form

I have the following form:
<form class="form-horizontal" {{action "formSubmit"}}>
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
As you notice, I have two actions for this form:
When I type on the user input field and press enter, it fires the findUser action
When the form submits, the formSubmit action is called.
Now, here's the problem.
When I type something on the user text field and press enter, it fires the findUser action but also fires the formSubmit. As I know, this is how a form normally behaves. When you press enter on a text field, it submits the form.
Is there a workaround on this behavior? That when I press enter on a the user text field, I want the findUser action to be fired but not submit the form.
Please help.
One workaround is removing form itself. You can have action on button. You may have to sacrifice some form related features but still works very well. Here is the jsbin.
http://emberjs.jsbin.com/nifim/2/edit
There might be some other better way as well.
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser" bubbles=false}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary" {{action "formSubmit"}}>Save</button>
and javascript
App.IndexController = Ember.Controller.extend({
actions: {
findUser: function(){
console.log('Find User');
},
formSubmit: function(){
console.log('Form Submit');
}
}
});
Another workaround that allows using the form:
http://emberjs.jsbin.com/povud/1/
Just add 'onkeypress="return event.keyCode != 13;"' to the form element and place the {{action}} on the button itself:
<form class="form-horizontal" onkeypress="return event.keyCode != 13;">
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button class="btn btn-primary" {{action "formSubmit"}}>Save</button>
</form>

jQuery.validationEngine v2.6.1 Only Validates Sometimes?

The code appears to be hooked up (like this)
jQuery("#contactForm").validationEngine();
because it will validate and raise an error bubble if:
you tab out of required field without any input
you type at least one character into a field that requires more and then click the submit button
But it will not validate and raise an error bubble if you do nothing at all except click the submit button. In that case, it just submits. Once you click in the field or enter anything at all, it seems to work.
What can I be looking for that I've mis-configured?
The HTML:
<form class = "contactform" id = "contactForm">
<fieldset>
<div class="contactform-name contactform-field">
<label class="contactform-label" for="contactform-name">Name:
<br>
</label>
<input class="validate[required,minSize[8]] contactform-input" type="text" id="contactform-name" name="name" />
</div>
<div class="contactform-email contactform-field">
<label class="contactform-label" for="contactform-email">Email Address:<br></label>
<input value class="validate[required,custom[email]] contactform-input" type="email" id="contactform-email" name="contactform-email" />
</div>
<div class="contactform-text contactform-field">
<label class="contactform-label" for="contactform-text">Message:
<br>
</label>
<textarea class="validate[required,minSize[12]]contactform-input" name="text" id="contactform-text" > </textarea>
</div>
<input class="contactform-button" type="submit" name="submit" value="Send" />
</fieldset>
</form>
The JavaScript (it's running in Meteor):
Template.Contact.rendered = function () {
jQuery("#contactForm").validationEngine();
}
I've never used this engine, but from the docs I found that 'attach' will attach the validator to form.submit. Can it be as simple as that?
https://github.com/posabsolute/jQuery-Validation-Engine#attach
EDIT:
You can also do stuff to the submit-event (if the tip above won't help).
Something like this (not tested, but should put you in the correct path):
Template.templateName.events({
'submit': function(event) {
// Prevent the submit with preventDefault()
event.preventDefault();
// Do something to check the submit etc.
}
});

Categories