Sweetalert PoP-up message when fields are field is not working - javascript

I had a question about Sweetalert a week ago. Then I got an answer which helped me, but unfortunately, it is still not working. I wanted a Sweetalert pop-up message (success) when the user hits the submit button, but only if the fields are filled. I do not know what the problem is. Currently, nothing happens when the user hits the button.
Here is my code:
function Sweetalert1(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var email = document.getElementById("email").value;
if (name != " " && message != " " && email != " "){
Swal.fire(
'Köszönjük!',
'Megkaptuk a leveledet és hamarosan válaszolunk!',
'success',
)}
}
And the part of the HTML:
<form role="form" id="contactForm" action="contact.php" method="post">
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Név</label>
<input class="form-control" id="name" name="name" type="text" placeholder="Név" required="required" data-validation-required-message="Kérlek add meg a neved!">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Email Cím</label>
<input class="form-control" id="email" type="email" name="email" placeholder="Email" required="required" data-validation-required-message="Kérlek add meg az Email címed!">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Üzenet</label>
<textarea class="form-control" id="message" rows="5" placeholder="Üzenet" name="message" required data-validation-required-message="Kérlek írd be az üzeneted!"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div id="success"></div>
<div class="form-group">
<button name="submit" type="submit" class="btn" id="sendMessageButton">Küldés</button>
</div>
</form>

I can't see where the button was fired
On this line,
<button name="submit" type="submit" class="btn" id="sendMessageButton">Küldés</button>
You have at least two options to fire the button
1st
You can change the line to this
<button name="submit" type="submit" class="btn" id="sendMessageButton" onclick="Sweetalert1()">Küldés</button>
2nd
You can add this to your javascript section
$("#sendMessageButton").click(function(){
Sweetalert1();
});
3rd
You can use the form's on-submit event
$("form").submit(function(){
Sweetalert1();
});
When this is done, modify your condition to
if (name !== "" && message !== "" && email !== "")
OR
if (name.trim() && message.trim() && email.trim())

your condition is not right, try doing this:
if (name && message && email)
{
// Code
}

An empty field isn't equal to a space (" "), it is equal to an empty string (""). So, you need to check if the fields equal an empty string, not a field with a space:
if (name != "" && message != "" && email != "") {
// code...
}
However, if you want to treat fields which have no text in them (and just spaces) as invalid as well, you can add the .trim() method to your name, message and email variables. By using trim you can turn inputs such as
" " into "", which will then be treated as an invalid input:
if (name.trim() != "" && message.trim() != "" && email.trim() != "") {
// code...
}
As an empty string is considered falsey (ie "" == false) you don't need to check whether you're input equals an empty string and instead can just check if x.trim() evaluates to true like so:
if (name.trim() && message.trim() && email.trim()) {
// code...
}

Related

How do I display a popup error/success message when needed?

This is a javascript code in the HTML file, there is also a mail.php file.
Main:
I'm trying to create an alert function using "SweetAlert".
I want the error message to show up when the form is not validated and the success message when it is (email sent).
Extra:
When the form is validated and the success message shows, the page reloads. Can the page reload only when I click on the "OK" button in the popup?
<form class="contact100-form validate-form alert" action="mail.php" method="POST">
<span class="contact100-form-title">
Contact
</span>
<div class="wrap-input100 rs1-wrap-input100 validate-input" data-validate="Name is required">
<span class="label-input100">Your Name</span>
<input class="input100" type="text" name="name" placeholder="Enter your name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 rs1-wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<span class="label-input100">Email</span>
<input class="input100" type="text" name="email" placeholder="Enter your email addess">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Message is required">
<span class="label-input100">Message</span>
<textarea class="input100" name="message" placeholder="Your message here..."></textarea>
<span class="focus-input100"></span>
</div>
<div class="container-contact100-form-btn">
<button class="contact100-form-btn">
<span>
Send
<i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i>
</span>
</button>
</div>
</form>
$('.alert').on('submit', function validateForm() {
var name = document.forms["Form"]["name"].value;
var email = document.forms["Form"]["email"].value;
var message = document.forms["Form"]["message"].value;
if (name == "" || email== "" || message == "" ) {
swal("Great!", "We'll get back to you soon!", "success");
swal("Oops!", "Fill the blanks correctly!", "error" );
}
});
Right now, I'm getting an error message popup when the form is both not filled (not validated) and filled (validated form is submitted and I received the email).
This is because you have both the alerts in the same block.
Try this:
if (name == "" || email== "" || message == "" ) {
swal("Oops!", "Fill the blanks correctly!", "error" );
}
else
swal("Great!", "We'll get back to you soon!", "success");
As, I see your code, there's no mention of "Form" in there..
Edit your code with this..
<form class="contact100-form validate-form alert" name="Form" ..then the rest of code
SweetAlert uses promises to keep track of how the user interacts with the alert.
If the user clicks the confirm button, the promise resolves to true. If the alert is dismissed (by clicking outside of it), the promise resolves to null.
swal("Great!", "We'll get back to you soon!", "success")
.then((value) => {
if(!value) {
return false;
}
});

How do i check that the textboxes and checkbox has been filled and checked before user can submit the form?

Below shown my JS code and part of the HTML that i wish to create the form. I can't find the reason of why i CAN still submit it when there are fields that are not filled. It should pop up a dialog box according to which fields the user has not fill.
<script>
function validation() {
if( $('#sdate').val() == null || $('#sdate').val() == undefined || $('#sdate').val() == "" ){
alert( 'Please fill in start date field');
}
if( $('#edate').val() == null || $('#edate').val() == undefined || $('#edate').val() == "" ){
alert( 'Please fill in end date field');
}
if( $('#agree').val() == null || $('#agree').val() == undefined || $('#agree').val() == ""){
alert( 'Please indicate that you have satisfied all the requirements');
}
}
</script>
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Start Date:</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date:</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>
<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" class="button" name="submit" value="submit" onclick="validation()" >
</div>
</div>
</div>
check box validation was wrong . Iis is(':checked') .And apply the input validation simple with !input value its validate null,empty,undefined ..trim() remove the unwanted empty spaces .
if you have from tag try with onsubmit="return validation()" instead of onclick="validation" submit button. return false its stop the function execution when the input fails
function validation() {
if (!$('#sdate').val().trim()) {
alert('Please fill in start date field');
return false // if you have a form tag
}
if (!$('#edate').val().trim()) {
alert('Please fill in end date field');
return false // if you have a form tag
}
if (!$('#agree').is(':checked')) {
alert('Please indicate that you have satisfied all the requirements');
return false // if you have a form tag
}
else{
console.log('ok')
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form onsubmit="return validation()">
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Start Date:</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date:</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>
<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" class="button" name="submit" value="submit" >
</div>
</div>
</div>
</from>
Try this, It will help you,
$("#btn").click(function()
{
if( $('#sdate').val() == null || $('#sdate').val() == undefined || $('#sdate').val() == "" ){
alert( 'Please fill in start date field');
return false;
}
if( $('#edate').val() == null || $('#edate').val() == undefined || $('#edate').val() == "" ){
alert( 'Please fill in end date field');
return false;
}
if(!document.getElementById('agree').checked) {
alert( 'Please indicate that you have satisfied all the requirements');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Start Date:</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date:</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>
<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" id="btn" class="button" name="submit" value="submit" onClientClick="validation()" />
</div>
</div>
</div>
</div>
You need to add return false after every alert. then It will prevent submit event and also it will show the alert message of appropriate field which is first position in the form. If it is not filled immediately the submit event is prevent rest of the alert messages are not shown even the field is empty.
you need to catch the form submit event. The return false statement in the if conditions will stop the event. If everything goes fine, no return false statement will be executed and the form will be submitted.
var validation = function() {
if( $('#sdate').val() == null || $('#sdate').val() == undefined || $('#sdate').val() == "" ){
alert( 'Please fill in start date field');
return false;
}
if( $('#edate').val() == null || $('#edate').val() == undefined || $('#edate').val() == "" ){
alert( 'Please fill in end date field');
return false;
}
if( !$('#agree').is(':checked') ){
alert( 'Please indicate that you have satisfied all the requirements');
return false;
}
}
$("form").submit(function(){
validation();
});

Javascript check if BOTH fields contain text

JS:
function check_form(){
var city = document.getElementById('sCity').value;
var region = document.getElementById('sRegion').value
if ((city != null || city !="") && (region != null || region !="")) {
alert('You can only search with a PostCode OR a City. Please remove either the City or PostCode.');
return false;
}
return true;
}
HTML:
<form action="<?php echo osc_base_url(true); ?>" method="get" class="nocsrf" onSubmit="return check_form()">
<fieldset>
<h3>City</h3>
<div class="row" id="wor1">
<input class="input-text" type="text" id="sCity" name="sCity" value="" />
</div>
</fieldset>
<fieldset>
<h3>Postcode</h3>
<div class="row" id="wor2">
<input class="input-text" type="text" id="sRegion" name="sRegion" value="" />
</div>
</fieldset>
<div class="actions">
<button type="submit">Apply</button>
</div>
</form>
FIDDLE
I need a way to check the two textfields above so that only ONE textfield can be text when the form is submitted. So if user types in a city + postcode, it will alert the user that the form can only take a postcode or a city.
I tried doing this myself but my code doesn't work...
Fix the condition to this:
if ((city != null && city !="") && (region != null && region !="")) {
Note the use of && for each of the two conditions instead of ||. This will make sure that the alert is shown when both fields are filled by the user.

JS/jQuery event.submit/return true not woking

I am wondering if someone can help me as i cant figure this out. I have this validation script that checks an email form for contents and valid email and it is working correctly however it is not submitting the form if everything is okay..it just removes to error messages and does nothing.
I have a strange feeling it will be something stupid but i cant see anything wrong here.
HTML
<!DOCTYPE html>
<html>
<head>
<?php include('includes/head.php'); ?>
<script type="text/javascript" src="js/contactVal.js"></script>
</head>
<body>
<?php include('includes/navbar.php'); ?>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Contact Form</h3>
<p>Use this handy little contact form to get in contact with me about anything at all. If you have a job offer or any questions about me then feel free to drop me a message, ill get back to you as soon as possible.</p>
<hr>
<div id="form-response">
</div>
<form id="mailer" action="scripts/mailer.php" method="POST">
<h3>Name:</h3>
<input type="text" id="name" name="name" placeholder="Enter your name"></input><br />
<h3>Email:</h3>
<input type="email" id="email" name="email" placeholder="Enter your email address"></input><br />
<h3>Subject:</h3>
<input type="text" id="subject" name="subject" placeholder="Enter the subject of your message"></input><br />
<h3>Message:</h3>
<textarea id="message" name="message" placeholder="Enter your message here..."></textarea><br />
<input type="submit" name="submit" id="submit" value="Send"></input><br /><br />
<input type="hidden" name="honeypot" id="honeypot" value="http://" />
<input type="hidden" name="human" id="human" value="" />
</form>
</div>
<div class="col-md-4">
<h3>Details</h3>
<p><img class="about-arrow" src="img/icons/arrow.png" />Email: contact#alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Website: www.alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Mobile: On request</p>
<hr>
<h3>Socials</h3>
<a class="big" href="http://www.facebook.com/oukp3ngu1nx"><img class="about-arrow" src="img/icons/arrow.png" />Facebook</a><br />
<a class="big" href="http://www.twitter.com/alex_volley_"><img class="about-arrow" src="img/icons/arrow.png" />Twitter</a><br />
<a class="big" href="https://www.linkedin.com/pub/alex-volley/97/27/906"><img class="about-arrow" src="img/icons/arrow.png" />LinkedIn</a><br />
</div>
</div>
</div>
<?php include('includes/footer.php'); ?>
</body>
</html>
JAVASCRIPT
$(document).ready(function(){
$('#form-response').hide();
$('#form-response').click(function(){
$('#form-response').fadeOut();
});
$('#submit').click(function(){
event.preventDefault();
var valid = '';
var name = $('form #name').val();
var email = $('form #email').val();
var subject = $('form #subject').val();
var message = $('form #message').val();
var honey = $('form #honeypot').val();
var human = $('form #human').val();
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
//check for human interaction
if(honey == 'http://' && human == ""){
//check fields
if(name == '' || null || name.length < 2){
valid = '<p>You need to enter your name.</p>';
}
if(email == '' || null || email.length < 5){
valid += '<p>You need to enter an email address.</p>';
}
if(!email.match(filter)){
valid += '<p>You need to enter a valid email address.</p>';
}
if(subject == '' || null || subject.length < 2){
valid += '<p>You need to enter a valid subject.</p>';
}
if(message == '' || null || message.length < 30){
valid += '<p>You need to enter a message of at least 30 characters.</p>';
}
//check if valid
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
return true;
}
} else {
//spambot
error = '<p>Back of bot boy.</p>';
}
});
});
You did not pass event in the function arguments:
$('#submit').click(function( event ){
event.preventDefault();
You're probably better off using the submit event and letting the submit button do it's job:
$('#mailer').submit(function( event ){
event.preventDefault();
........
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
this.submit(); //ONCE EVERYTHING CHECKS OUT
} else {
.....
JS FIDDLE DEMO
EDIT
To resolve the error Uncaught TypeError: object is not a function, please change the name of your submit button to something else: this.submit -- the button, is conflicting with this.submit() -- the function.
Here is a version that works fine after changing: name="submit" to name="submit-button"
By the way your input elements do not need a closing tag </input>
REF: Uncaught TypeError: object is not a function, button inside form
May be you can try following code. On Submit button click validate form and if everything is fine submit form using .submit method.
$('#submit').click(function( event ){
event.preventDefault();
............
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
$('#mailer').submit(); //ONCE EVERYTHING CHECKS OUT
}
..............

How to validate a page using jQuery for passwords

I have a div and it contains three input text boxes(oldpassword,newpassword,confirmpassword).
<div class="searchContainer" id="chngpassword">
<div class="tableContent">
<div class="leftContent">
<div>Old Password<span class="redCLR">*</span></div>
<div>New Password<span class="redCLR">*</span></div>
<div>Confirm Password<span class="redCLR">*</span></div>
</div>
<div class="rightContent">
<div><input type="password" name="OldPassword" id="OldPassword" /></div>
<div><input type="password" name="NewPassword" id="NewPassword" /></div>
<div><input type="password" name="ConfirmPassword" id="ConfirmPassword" /></div>
</div>
</div>
<div class="searchButton" style="margin:10px 0 0 0">
<button id="btnSave">SAVE</button>
</div>
</div>
Now i have to validate the page in jquery for following scenarios:
1.Old password should not be blank.
2.New password should not be blank.
3.confirm password should not be blank.
4.old and confirm password should be same.
5.new password length should be 8-16 characters,atleast 1 special character,atleast 1 upper case,atleast 1 numericvalue.
Here is a quick solution that I think is what you are looking for . . .
function validatePassword(){
var old_pass = $('#OldPassword').val();
var new_pass = $('#NewPassword').val();
var conf_pass = $('#ConfirmPassword').val();
if(old_pass === ""){
alert('Old password should not be blank.');
}
else if(new_pass === ""){
alert('New password should not be blank.');
}
else if(conf_pass === ""){
alert('Confirm password should not be blank');
}
else if(!new_pass.match(/(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{8,16}$/))
alert('New password length should be 8-16 characters,atleast 1 special character,atleast 1 upper case,atleast 1 numericvalue');
}
else if(new_pass !== conf_pass){
alert('New and confirm password should be same');
}
return false
}
This should do it. I have it on JSFiddle if you want to see it working

Categories

Resources