setCustomValidity on .ajaxForm() beforeSubmit - javascript

I'm loading a form into a modal dialog on button click and attaching .ajaxForm() to it on load. ajaxForm() has a beforeSubmit function in which I call two functions to validate username and password fields and setting .setCustomValidity() on them. I imagined it would go something like this; clicking Submit validation is done in beforeSubmit and setCustomValidity is set on invalid fields; then, a message appears on submit attempt.
However, messages appear only after I click Submit the second time. The first time it does nothing.
This is the form.
<form method="POST" action="/scripts/register.php" id="register-form">
<input minlength="6" maxlength="15" type="text" id="user" name="user" oninput="setCustomValidity('')" placeholder="Username" required>
<input minlength="6" maxlength="15" type="password" id="pass" name="pass" oninput="setCustomValidity('')" placeholder="Password" required>
<input minlength="6" maxlength="15" type="password" id="confirm_pass" name="confirm_pass" oninput="setCustomValidity('')" placeholder="Confirm Password" required>
<input type="email" id="email" name="email" placeholder="E-mail" required>
<input type="submit" name="login" class="button" value="Login">
</form>
Loading form into a dialog
$( "body" ).on("click","#register",function(){
$(".modal-dialog").load("register-form.php", function(){
$('#register-form').ajaxForm({
beforeSubmit : function(){
check_password_validity();
check_username_validity();
}
});
});
$( ".dialog-overlay" ).addClass( 'dialog-overlay-open' );
});
And the two functions where I setCustomValidity:
function check_password_validity(){
var pass = $("#pass").val();
var pass2 = $("#confirm_pass").val();
if(!is_alnum(pass)){
$("#pass")[0].setCustomValidity("Samo alfanumerički znakovi, bez razmaka i posebnih znakova.");
return;
}
if(pass!=pass2){
$("#confirm_pass")[0].setCustomValidity("Lozinke se ne podudaraju!");
return;
}
}
function check_username_validity(){
var user = $("#user").val();
if(!is_alnum(user)){
$("#user")[0].setCustomValidity("Samo alfanumerički znakovi, bez razmaka i posebnih znakova.");
return;
}
$.post( "/scripts/check_username_exists.php", {username: user}, function( data ) {
if(data=="true"){
$("#user")[0].setCustomValidity("Korisnik s tim imenom već postoji.");
return;
}
});
}
This works and all, but the messages appear on second submit attempt, after Submit buttons is clicked the second time. It seems like I'm missing something simple but can't figure out what it is.

Related

how to make swal wait for button click?

I am using swal("") to inform a visual message to the user after a form is submitted.
The code works however the element swal disappears instantly, if I use alert("") the code works. But the goal would be to make it work with swal("").
let form = document.getElementById("form");
form.addEventListener("submit", (e) => {
valid = form.checkValidity();
if(valid) {
swal({
title:"Registro Salvo!",
text:"Navegue até dados de natalidade para visualizar.",
icon:"success",
button:"Ok" }
);
return false;
}
else {
return true;
}
});
<form id="form" action="index.html" method="POST">
<label for="FirstName">First Name:</label>
<input type="text" id="FirstName" placeholder="First Name" />
<label for="LastName">Last Name:</label>
<input type="text" id="LastName" placeholder="Last Name" />
<input type="Submit" value="Submit" />
</form>
With how your code works now, your swal message is confirming that your form has been submitted, but not a guarantee that it has been received successfully.
If you are OK with this functionality then you can get probably get around the issue your facing by changing the submit button to a regular button and calling submit() yourself.
I've not used sweetalert (so the below code may not work, I have not tested it), but looking at the documentation you should be able to use .then() to capture the close/ok on your message box, so you can show the message and then actually submit the form when the user closes the message box.
let button = document.getElementById("submit_button")
let form = document.getElementById("form")
button.addEventListener("click", (e) => {
e.preventDefault();
swal({
title:"Registro Salvo!",
text:"Navegue até dados de natalidade para visualizar.",
icon:"success",
button:"Ok" }
).then( () => {
form.submit()
})
})
<form id="form" action="index.html" method="POST">
<label for="FirstName">First Name:</label>
<input type="text" id="FirstName" placeholder="First Name" />
<label for="LastName">Last Name:</label>
<input type="text" id="LastName" placeholder="Last Name" />
<input type="button" value="Submit" id="submit_button" />
</form>

Function only works when called through chrome console

I've got a JavaScript function that's supposed to be executed when an HTML button is clicked. The HTML for the form is
<form id="inputData">
Email:<br>
<input id="email" type="email" name="email"><br>
Username:<br>
<input id="username" type="text" name="username"><br>
Password:<br>
<input id="password" type="password" name="password"><br>
<input id="submit" type="submit" value="submit" onClick="getData()">
</form>
The related js code is
<script type="text/javascript">
function getData() {
var input = document.getElementById("inputData");
var email = input[0].value;
var user = input[1].value;
var pass = input[2].value;
sendData(user,email,pass)
}
function sendData(user,email,pass) {
var fireRef = firebase.database().ref("users/" + user);
fireRef.set({
emailAddress: email,
password: pass,
});
}
</script>
In debugger mode, the function gets executed when the submit button is clicked, and there are no errors, all of the form data is properly collected, yet the data never gets sent to the Firebase database. However, if i call the sendData function through the console and manually provide data in the arguments, it works perfectly. Can anyone think of why this might be happening?
onClick event isn't triggering
try
<form id="inputData" onsubmit="getData()">
Email:<br>
<input id="email" type="email" name="email"><br>
Username:<br>
<input id="username" type="text" name="username"><br>
Password:<br>
<input id="password" type="password" name="password"><br>
<input id="submit" type="submit" value="submit">
</form>

New recaptcha not filling in g-recaptcha-response

I have a registration page that requires the user to fill in a noCaptcha reCaptcha, but the widget is not filling in the g-recaptcha-response field. When I submit the form, my Node app is using a script I wrote to submit the response to Google and verify that the captcha is valid. That part is correct, but the recaptcha widget just won't fill out the response textarea it adds to the page. However, the jQuery I wrote that checks the value of the response field lets the page go through if the captcha is checked, but not if it is unchecked like it is supposed to, but the field is still not filled out.
What I need: To find out why reCaptcha isn't filling out the field when I POST the form to my backend.
Below is my register page's code and the jQuery running the page:
<div id="registerCard" class="login-card">
<p class="profile-name-card">Narrify Account Registration</p><br>
<form id="registerForm" action="/register" method="post" role="form" data-toggle="validator" class="form-signin has-validation-callback">
<input type="text" name="firstName" required="" placeholder="First name" autofocus="" class="form-control">
<input type="text" name="lastName" required="" placeholder="Last name" class="form-control">
<input id="inputRegistrationEmail" type="email" name="email" required="" data-validation="email" placeholder="Email address" class="form-control">
<input type="email" required="" data-validation="confirmation" data-validation-confirm="email" placeholder="Email repeat" class="form-control">
<input id="inputRegistrationPassword" type="password" name="password" required="" data-validation="strength" data-validation-strength="2" placeholder="Password" class="form-control">
<input type="password" required="" data-validation="confirmation" data-validation-confirm="password" placeholder="Password repeat" class="form-control">
<div data-sitekey="[MYSITEKEY]" class="g-recaptcha"></div><br>
<button type="submit" class="btn btn-primary btn-block btn-lg btn-signin">Register</button>
</form>
<a id="login-link" href="#" onclick="showLoginForm()" class="forgot-password">Login</a>
</div>
The jQuery:
$(function() {
// Switch to either load an avatar from autocomplete or remove the loading bar
if($("#inputEmail").val() != "") {
updateAvatar();
} else {
$("#image-progress").fadeOut();
}
// Event Handlers for links and inputs
$("#inputEmail").change(updateAvatar);
var url = window.location.pathname;
if(url.substring(url.lastIndexOf("#") + 1) == "register")
showRegisterForm();
$.validate({ modules: "security" });
$("#registerForm").submit(function(e) {
var recaptcha = $("#g-recaptcha-response").val();
if(recaptcha == "") {
e.preventDefault();
alert("Please complete the captcha");
}
});
});
function updateAvatar() {
// Show the loading bar until it is removed by a new image loading
$("#image-progress").fadeIn();
// Set the avatar image based on the input of the Email field
$("#profile-avatar").attr("src", "https://secure.gravatar.com/avatar/" + md5($("#inputEmail").val().toLowerCase()) + "?d=identicon&r=pg");
// Set event handler to hide loading bar once the image loads
$("#profile-avatar").on("load", function() {
$("#image-progress").fadeOut();
});
}
function showResetForm() {
alert("test");
}
function showRegisterForm() {
$("#loginCard").fadeOut();
$("#registerCard").fadeIn();
}
function showLoginForm() {
$("#registerCard").fadeOut();
$("#loginCard").fadeIn();
}

window.onload method, how to call multiple functions

Writing some JavaScript so the form does not submit in less the fields have been filled out, and if the user has not, a message pops up saying 'please fill out the name field' or 'please fill out the email field' etc. I am writing a separate function for each field (don't know if that is the right way) and when I add each function to the window.onload, it only pops up with one of the messages. Any advice would be great.
HTML
<form id="frmContact" name="frmContact" method="post" action="thanks.htm">
<fieldset id="quickSupport">
<legend><strong>Quick Support</strong></legend>
<p> If your request isn't urgent, drop us a quick line and we'll get back to you within 24 hours </p>
<p>
<label for="name">Name:</label>
<input type="text" value="Your Name" name="name" id="name" tabindex="10" />
</p>
<p>
<label for="email">Email:</label>
<input type="text" value="Your Email" name="email" id="email" tabindex="20" />
</p>
<label for="comments">Comments </label>
<br />
<textarea name="comments" value="Message" id="comments" cols="45" rows="5" tabindex="60" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;">Message</textarea>
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send" tabindex="70" />
</p>
</fieldset>
</form>
<p><span id="errorMessage"></span></p>
<p><span id="errorMessage1"></span></p>
JavaScript
function prepareEventHandlers () {
document.getElementById("frmContact").addEventListener("submit", function(event) {
// Show message
if (document.getElementById("email").value == "Your Email") {
document.getElementById("errorMessage").innerHTML = "Please provide at least an email address!";
// to STOP the form from submitting
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage").innerHTML = "";
return true;
}
event.preventDefault(); // Prevent form from submitting
}
});
}
function prepareEventHandlersName () {
document.getElementById("frmContact").addEventListener("submit", function(event) {
// Show message
if (document.getElementById("name").value == "Your Name") {
document.getElementById("errorMessage1").innerHTML = "Please provide a name!";
// to STOP the form from submitting
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage1").innerHTML = "";
return true;
}
event.preventDefault(); // Prevent form from submitting
}
});
}
function start() {
prepareEventHandlers();
prepareEventHandlersName();
}
window.onload = start;
You should use the browser's built-in validation attributes.
<form id="frmContact" name="frmContact" method="post" action="thanks.htm">
<fieldset id="quickSupport">
<legend><strong>Quick Support</strong></legend>
<p>If your request isn't urgent, drop us a quick line and we'll
get back to you within 24 hours</p>
<p>
<label for="name">Name:</label>
<input type="text" value="Your Name" name="name" id="name"
tabindex="10" required />
</p>
<p>
<label for="email">Email:</label>
<input type="text" value="Your Email" name="email" id="email"
tabindex="20" required />
</p>
<label for="comments">Comments</label>
<br />
<textarea name="comments" value="Message" id="comments" cols="45"
rows="5" tabindex="60"
placeholder="PLACEHOLDER WHEN NO MESSAGE IS WRITTEN" required>Message</textarea>
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send"
tabindex="70" />
</p>
</fieldset>
</form>
When you try to submit the form, the browser will automatically display nice error messages for you, in the user's language. No JavaScript required.
The reason your code is failing, because
document.getElementById("frmContact").onsubmit = ...
will override any previous onsubmit handler you've added.
You need to use .addEventListener() instead, if you want to add multiple functions.
A more correct way would be to create a single function that does all checks, and attach that as the handler, once.
Both functions are running, but you're overwriting the onsubmit handler for frmContact in your second function. To avoid this, don't assign event handlers that way. Instead, use addEventListener.
document.getElementById("frmContact").addEventListener("submit", function(event) {
if (document.getElementById("email").value == "Your Email") {
// Show message
event.preventDefault(); // Prevent form from submitting
}
});
Note that when you do it this way, you can't prevent the form from submitting by simply returning false. Instead, you have to use the event's preventDefault method.

Have to remove submit button to get js to work

I'm trying to validate login details from an html form. The problem is that the submit button doesn't work with the code. So for example if I leave the username and password blank it won't come up with an alert for "Invalid Username or Password". If I remove type="submit" it works but the button becomes an input text box with an onclick function which does not look good. I was provided with this code as it is a more secure way of passing login details than I had written so I have to confess my ignorance on JS and JSON so apologies if I haven't provided enough info but any guidance would be much appreciated on how to get the button working with the js. This is running on Chrome only. Cheers.
HTML code
<form name="login" id="login-form">
Username<input name="username" id="username" data-bind="value: username" type="text" value="" />
Password<input name="password" id="password" data-bind="value: password" type="password" value="" />
<input name="submit" type="submit" onclick="myApp.getLogin()" value="Login" />
</form>
JS
myApp.getLogin = function(){
var url = "http://localhost:8084/Alumni_JV1/services/login.json?username=" + myApp.vm.username()
+ "&password=" + myApp.vm.password();
console.log(url);
$.getJSON( url, function( data ) {
if(data.response==='success'){
window.location.href="profile.jsp";
}else{
alert("Invalid Username or Password");
}
});
};
A submit button is used to send form data to a server. E.G. <form action='formHandler.php'>. It would submit the form to the current URL if the action attribute isn't defined.
You can get a button without any action with <input type='button' />.
So changing <input type='submit' ... to <input type='button' ... should do the trick :)
Then the code would be:
<form name="login" id="login-form">
Username<input name="username" id="username" data-bind="value: username" type="text" value="" />
Password<input name="password" id="password" data-bind="value: password" type="password" value="" />
<input name="submit" type="button" onclick="myApp.getLogin()" value="Login" />
</form>
Change input type=submit field with button tag.

Categories