how to make swal wait for button click? - javascript

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>

Related

Hide/locking a <form> button until form is completely filled with validation

I make my JSON script with a form and a button, but when I demo it on someone, they can press the submit button whenever they like. Here is my code:
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br>
</form>
All I need now is validation and how to lock or hide the button. I tried using <script> with function and getElementById but I simply do not know how to lock it. Here is the message that will be inputted when it is locked and the form isn't completed:
You have not finished the information input for the survey. Please
input "Your First Name" and "Your Last Name" to enter the survey.
When they finish, I will input a loading icon until fully loaded.
Code Language(s)
I use fiddles to make my code, so I use:
HTML
JSON
Pinch of jQuery (loading icon)
Answer Expectations
In my answers, I need:
Recommended Code Language
Code for note purposes
Crossed out attributes
Attributes before coding explanations
EDIT: I just noticed that I can use the disabled boolean attribute here, so all I need is validation to disable the boolean attribute so they can press the button.
Hello I recommend JavaScript but it is not secure at all. However its the most effective in this case. Here is the code: (Note that i changed the html too)
<form action="action_page.php" method="get" >
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="inputEntries()"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" onkeyup="inputEntries()"><br><br>
<button type="submit" name="submit" id="submit_btn" disabled="true">submit</button>
</form>
<script>
var fname_var = document.getElementById("fname");
var lname_var = document.getElementById("lname");
var submit_btn_var = document.getElementById("submit_btn");
function inputEntries(){
if(lname_var.value != "" && fname_var.value != "")
submit_btn_var.disabled = false;
else
submit_btn_var.disabled = true;
}
</script>
What it does is that if both input fields are empty the button is not clickable but if both are it can be clicked. hope it helped!
You can use either pure javascript or jQuery to validate.
In the below code you would see we are first binding a change event to the input field and getting its values. If both values are present, the disabled attribute of the submit button is removed. Else the opposite.
<p id="msg">You have not finished the information input for the survey. Please input "*Your First Name*" and "*Your
Last Name*" to enter the survey.</p>
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br><br>
<button type="submit" id="btn-submit">Submit</button>
</form>
$(document).ready(function(){
('#btn-submit').prop('disabled', true);
$("input[type=text]").change(function(){
if ($('#fname').val() && $('#lname').val()) {
$('#btn-submit').prop('disabled', false);
$('#msg').hide();
} else {
$('#btn-submit').prop('disabled', true);
$('#msg').show();
}
});
});
Stackblitz - https://stackblitz.com/edit/jquery-kgzhuo?file=index.html

setCustomValidity on .ajaxForm() beforeSubmit

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.

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.

How to get data from form to javascript and redirect to another page?

I have a html5 form with name, surname ect. The reason why I'm using a form is so that the user has to fill in everything, for that I'm using required. I want to save all the data in localStorage, for that I need to move the data to JavaScript.
How do access the data in JavaScript when the submit button is pressed while redirecting the user to another page?
This is the code:
Html5
<form id="TheForm" method="post">
<input type="text" id="Name" placeholder="*Förnamn" required >
<input type="text" id="Surname" placeholder="*Efternamn" required >
<input type="email" id="FirstEmail" placeholder="*e-postadress" autocomplete="on" required >
<input type="email" id="SecondEmail" placeholder="*Verifiera e-postadress" autocomplete="off" required >
<input type="text" id="Address" placeholder="*Adress" required >
<input type="submit" id="Submit" onclick="function()" value="Skicka">
</form>
var submit = function () {
window.localStorage.name = document.getElementById('Name').value;
// Save all the other fields
// You either return a non-false value here and let the form submit
// Or you return false and do a window.location change
};
window.onload = function () {
var form = document.getElementById('TheForm');
if (form.attachEvent) {
form.attachEvent('submit', submit);
} else {
form.addEventListener('submit', submit);
}
}
Try this
Java Script
function storeDetails() {
if(typeof(Storage)!=="undefined") {
localStorage.setItem('name', document.getElementById('Name').value));
//code to store other values will go here
} else {
alert('Your browser do not support local storage');
}
}
HTML
<form id="TheForm" method="post" onsubmit="javascript:storeDetails();" action=" ">
<input type="text" id="Name" placeholder="*Förnamn" required >
<input type="text" id="Surname" placeholder="*Efternamn" required >
<input type="email" id="FirstEmail" placeholder="*e-postadress" autocomplete="on" required >
<input type="email" id="SecondEmail" placeholder="*Verifiera e-postadress" autocomplete="off" required >
<input type="text" id="Address" placeholder="*Adress" required >
<input type="submit" id="Submit" onclick="function()" value="Skicka">
</form>

Categories