Subscription button with data validation - javascript

What the script does is hide the input element and show the "thanks message".
But prior to this I need it to validate if input emailfield is validated, and show the "thanks message" only if that happens.
Thanks!
var nextStep = document.querySelector('#nextStep');
nextStep.addEventListener('click', function(e) {
e.preventDefault()
// Hide first view
document.getElementById('my_form').style.display = 'none';
// Show thank you message element
document.getElementById('thank_you').style.display = 'block';
});
<form class="row row-cols-lg-auto g-2 align-items-center justify-content-end">
<div class="col-12" id="my_form">
<input id="emailfield" type="email" class="form-control" placeholder="Ingresa tu Email" required="required">
</div>
<div class="col-12" id="thank_you" style="display: none;">
Gracias por subscribirse!
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary-soft m-0" name="subscribirse" id="nextStep">Subscribirse</button>
</div>
</form>

var nextStep = document.querySelector('#nextStep');
nextStep.addEventListener('click', function (e) {
e.preventDefault()
let inputEmail = document.querySelector('#emailfield')
if (/.*\#.*\..*/.test(inputEmail.value)) {
// validation passed
// Hide first view
document.getElementById('my_form').style.display = 'none';
// Show thank you message element
document.getElementById('thank_you').style.display = 'block';
} else {
// validation not passed
}
});
Instead of this regexp you can use any that you want

Related

How to properly write a javaScript toggle hide/show function for 2 forms (Registration and Login form) without refreshing a page or link to new html

I went through all similar questions but none of them seem to help me with what I want to do. Maybe I am just missing something and if there is a question out there that could help could you please point me to that question and I will delete this. Anywhoo...
I am trying to create a function that when I click a link on the bottom of the login form (Need an account? Register) it will hide the Login form and show the Registration form with a link on the bottom of the Registration form (Have an account? Login) to go back to the Login form without refreshing the page or going to a new html page.
I have tried multiple things... I want it to look like this... I have set the display to none for my registration form and the display for my login form to block.
example of login to registration and back
This is two of the codes I have tried.
Example one that seems right but is wrong:
function showAndHide() {
const loginBtn = document.getElementById('loginbtn');
const signupBtn = document.getElementById('signupbtn');
const regForm = document.getElementById('register');
const logForm = document.getElementById('login');
if (regForm.style.display == 'none') {
regForm.style.display = 'block';
logForm.style.display = 'none';
} else {
logForm.style.display = 'block';
regForm.style.display = 'none';
}
loginBtn.addEventListener('onclick', function() {
showAndHide(loginBtn);
});
signupBtn.addEventListener('onclick', function() {
showAndHide(signupBtn);
});
Example two that seems right but is wrong:
function showAndHide() {
const regForm = document.getElementById('register');
const logForm = document.getElementById('login');
if (regForm.style.display = 'none') {
regForm.style.display = 'block';
logForm.style.display = 'none';
} else {
logForm.style.display = 'none';
regForm.style.display = 'block';
}
}
My Html:
<body>
<section id="login">
<h2>Login</h2>
<form id="login-form" method="post" novalidate>
<div>
<label for="logfield">Email:</label>
<input type="email" name="logfield" id="logfield" required>
</div>
<div>
<label for="pw">Password:</label>
<input type="password" name="pw" id="pw" size="15" required>
</div>
<div>
<button type="submit">LOGIN</button>
</div>
<div>
Need an account? Register
</div>
</form>
</section>
<section id="register">
<h2>Register</h2>
<form id="register-form" method="post" no validate>
<div>
<label for="email-field2">Email:</label>
<input type="email" name="email-field2" id="email-field2" required>
</div>
<div>
<label for="pw2">Password:</label>
<input type="password" name="pw2" id="pw2" size="15" required>
</div>
<div>
<label for="pw3">Repeat Password:</label>
<input type="password" name="pw3" id="pw3" size="15" required>
</div>
<div>
<button type="submit">REGISTER</button>
</div>
<div>
Have an account? Log in
</div>
</form>
</section>
</body>

How to create a modal only if the required fields are filled out before submitting form

I am trying to make a modal appear thanking the user for submitting the form but only if they completely filled out all the required inputs. I like the built in required feature in HTML but currently both pop ups happen when the submit button is pressed. I know an if else statement is required but cannot figure out how to show that the required field is satisfied in JS before popping up the modal.
<!-- THIS IS THE CONTACT FORM SECTION -->
<section class="contact-form">
<h1 class="uptop">CONTACT ME</h1>
<form method="get">
<input type="text" class = "name required" id="name" placeholder="NAME" required>
<input type="email" class="email required" id="email" placeholder="EMAIL" required>
<textarea id="message" class="message required" rows="5" cols="300" placeholder="MESSAGE"></textarea>
<input type="submit" class="submit" id="submit" value="Tell Me Something Good" >
</form>
</section>
<!-- The Modal -->
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p class ="modal-message">THANKS FOR THAT!</p>
</div>
</div
JavaScript:
var modal = document.getElementById('myModal');
var btnSubmit = document.getElementById("submit");
var spanClose = document.getElementsByClassName("close")[0];
var requiredFields = document.getElementsByClassName("required").required;
btnSubmit.onclick = function() {
modal.style.display = "block";
}
spanClose.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
I think this could help
The innerHTML will do the job
function check(){
var name = document.getElementById('name').value;
if(name!=''){
setStatus("Success");
}else{
setStatus("Error");
}
}
function setStatus(message){
var inputStatus = document.getElementById('msg');
inputStatus.innerHTML = message;
}
<input id='name' name='name' /><span id="msg"></span>
<button type="submit" onClick="check()">Send</button>

Onclick html call for JavaScript function not working in Safari

I am trying to call a function in my javascript file from an onclick event in html. This code works perfectly in Google Chrome but does not work in Safari as it redirects to the same page and empties the form, without redirecting to the home page of my website.
Here is my HTML code:
<!-- Login or subscribe form-->
<div class="py-5">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card text-white p-5 bg-primary signUpBoxStyle">
<div class="card-body">
<h1 class="mb-4">Effettua il login o iscriviti</h1>
<form>
<div class="form-group"> <label>Indirizzo email</label>
<input type="email" class="form-control" placeholder="Inserisci email" id="email"> </div>
<div class="form-group"> <label>Password</label>
<input type="password" class="form-control" placeholder="Password" id="password"> </div>
<input type="button" class="btn btn-light text-primary btn-sm" value="Accedi" onclick="loginFunction()">
<input type="button" class="btn btn-light text-primary btn-sm" value="Crea un Account" onclick="signupFunction()"> </form>
</div>
</div>
</div>
</div>
</div>
</div>
And this is my JavaScript
function loginFunction() {
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
})
};
You might need to tell the browser not to carry out the default behavior of that element via preventDefault(). This SO answer give a little more detail.
Having an if statement to check the attribute is not that scalable but it may be possible that you pass the function call as a parameter.
let buttons = document.querySelectorAll('input[type=button]')
buttons.forEach(button => {
button.addEventListener('click', e => {
let func = e.target.getAttribute('data-call')
if (func === 'login') {
loginFunction()
} else if (func === 'signup') {
signupFunction()
}
})
})
let loginFunction = () => {
console.log('loginFunction')
}
let signupFunction = () => {
console.log('signupFunction')
}
<form>
<input type="button" value="Accedi" data-call="login">
<input type="button" value="Crea un Account" data-call="signup">
</form>

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

field empty error for pop-up form

Can I have yout help pleas there,I make a validation field for a popup form :
function prepareEventHandlers() {
document.getElementById("contact").onsubmit = function () {
if (document.getElementById("message").value == '') {
document.getElementById("errorMessage").innerHTML = 'the field should not be empty!';
return false;
}
else {
document.getElementById("errorMessage").innerHTML = '';
return true;
}
};
}
window.onload = function () {
prepareEventHandlers();
}
then the html code :
<div id="form-content" class="modal hide fade in" style="display: none;">
<div class="modal-body">
<form class="contact" name="contact" >
<label class="label" for="message">Enter a Message</label><br>
<textarea id="message" name="message" class="input-xlarge"></textarea>
<p><span id="errorMessage"></span></p>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
No!
</div>
and I got this error :
TypeError: document.getElementById(...) is null document.getElementById("contact").onsubmit = function () {
Any Idea?
Edit:
OK I add id="contact" to my form so the error is gone but now the popup form is displyaed but when I try to click send with empty or not empty value nothing is happened...
just close </form> after <input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
and change html form id to contact

Categories

Resources