Modal pop up one time per user - javascript

In my website, I am using a simple modal popup with some input controls ( name, email, button).
The purpose of modal popup is:
After filling all mandatory fields, if user press "submit" button they will get one .pdf file.
I launch the modal upon onload.
Here, I am trying to do:
Open the modal popup only once for a user, or
Don't want to show the modal popup to users who previously filled out the form already
Here is the code of my modal popup:
<script type="text/javascript">
$(document).ready(function () {
$("#eBookModal").modal('show');
});
</script>
<div class="modal fade" id="eBookModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="row">
<h4 class="modal-title text-center" style="color:#FFFFFF;">Download eBook</h4>
</div>
</div>
<div class="modal-body">
<form role="form" id="eBookform" class="contact-form"
action="file.pdf">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control form-text" name="FName" autocomplete="off" id="eBook_FName" placeholder="First Name" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control form-text" name="LName" autocomplete="off" id="eBook_LName" placeholder="Last Name" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="email" class="form-control form-text" name="email" autocomplete="off" id="eBook_email" placeholder="E-mail" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center" id="eBook_download">
<button type="submit" class="btn main-btn" style="color:#fff !important;">Download Now</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>

You have to keep record of the modal displays. To store that info, you can either use a cookie or the localStorage. Based on the stored value, you can decide whether to show the modal or not.
The sample below uses the localStorage as an example:
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#eBookModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#eBookModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});
Available as a Codepen too.
If you would like to hide the modal just from those who already submitted the form, you should set the flag upon form submit, like so:
$('#eBookform').on('submit', function (event) {
// event.preventDefault();// depending on your use case
localStorage.setItem(key, true);
})
Note: to reset the stored value, just call localStorage.removeItem('hadModal').

If you just to show the modal one time for first time visit and previous code didn't work try this !
$(window).load(function(){
var Modal = document.getElementById('myModal');
var key = 'hadModal',
hadModal = localStorage.getItem(key);
if (!hadModal) {
Modal.style.display = "block";
localStorage.setItem(key, true);
}
});

if (document.cookie.indexOf("ModalShown=true")<0) {
jQuery(document).ready(function() {
setTimeout(function(){
$("#homepageModal").addClass("modal-show")
}, 1000);
});
var date = new Date(),
expires = 'expires=';
date.setDate(date.getDate() + 1);
expires += date.toGMTString();
document.cookie = 'ModalShown=true ;' + expires + '; path=/';
}

How do you get this script to work in Bootstrap 5 without using jQuery?
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#eBookModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#eBookModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});

Related

Check if username exist?

I have function that will be triggered on blur and send ajax request to check if username already exist in database. So far function works fine but I found one problem when user tries to update already saved username. Here is example of my code:
var usernames = ["jcook","mjones","kruffy"];
$(".check-account").focus(function() {
var submitBtn = $(this).closest("form").find(":submit");
submitBtn.prop("disabled", true); //Disable submit button on field focus.
$(this).attr('data-prev', $(this).val()); // Save current value in data attribute as data-prev.
if(!$(this).data("original")){
$(this).data("original",$(this).val());
}
}).blur(function() {
var fldObj = $(this),
submitBtn = $(this).closest("form").find(":submit");
if (fldObj.val() !== fldObj.data('prev') && fldObj.val() !== fldObj.data("original")) {
if ($.inArray(fldObj.val(), usernames) === -1) {
fldObj.data("original","");
fldObj[0].setCustomValidity("");
} else {
fldObj[0].setCustomValidity("User name already exist.");
}
submitBtn.prop("disabled", false);
} else {
fldObj[0].setCustomValidity("");
submitBtn.prop("disabled", false);
}
});
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frmSave" id="frmSave">
<input type="hidden" class="form-control" name="frm_recordid" id="frm_recordid">
<div class="form-group required">
<label class="control-label" for="username"><span class="label label-default">UserName:</span></label>
<input type="text" class="form-control check-account is-user" name="frm_username" id="frm_username" maxlength="50" required>
</div>
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-1 col-lg-1">
<button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-11 col-lg-11">
<div id="frm_message" class="alert"></div>
</div>
</div>
</form>
If you run my code example above you will see that my function will catch username if already exist. The problem that I have is when I try to edit data. Let's say I open form and user name will have value jcook. Then I try to enter different username for example mjones. If I try to submit form I will get message Username already exist!. Then if I try to put jcook again my code will trigger same message even I just try to put the same value that was already in the field for that record. I'm wondering how to avoid function trigger in this case if username was already saved for that record?

Firebase Chat change reference with javascript

I am trying out how to incorporate firebase with angular in such a way that the user is able to change the "Channel" of the chat via selecting from a dropdownlist.
This is the code that I have at the moment:
Note: The channel attribute is defined in another portion of code, and the entire page is loaded only once.
app.controller('mychat', function($scope, $firebaseArray) {
var d = new Date();
var today = d.getDate()+d.getMonth()+d.getYear();
var txt = document.getElementById('txtFBMsgs'); //store id of textbox
//Query
var ref = firebase.database().ref().child(channel)
$scope.fbmessages = $firebaseArray(ref);
$scope.send = function() {
if (txt.value != ""){ //check if textbox contains any message
$scope.fbmessages.$add({
sender: sender,
message: $scope.messageText,
date: Date.now()
})
txt.value = ""; //reset value of textbox
}
}
})
and here is my html portion:
<div class="card mb-1 col-md-3" ng-controller="mychat" id="myDiv">
<div class="card-body" style="overflow-x: hidden; overflow-y:scroll; min-height:60vh; max-height:64vh;">
<div>
<p ng-repeat="m in fbmessages"> {{m.date | date:'short'}} - {{m.sender}}: <br> {{m.message}}</p>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-9">
<input type="text" id = "txtFBMsgs" class="form-control" placeholder="Message here..." ng-model="messageText" onkeydown = "if (event.keyCode == 13) document.getElementById('sendBtn').click()">
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-primary btn-block" id="sendBtn" ng-click="send()">Send</button>
</div>
</div>
basically, it is a div that displays the chat messages, and an input box which is able to send the message to firebase.
Can I change the 'Channel' dynamically via javascript, such as on an onchange in a DDL?

Trying to prevent modal close on button click - javascript

I'm working on a small project in ASP.NET MVC, and in one part I need help of javascript.
Acctually there is modal with three inputs, old password, new and confirm new password,
and in case all fields are empty I need to prevent user from closing modal, I tried to solve it like this:
function comparePasswords(currentPassword) {
//Here I will loop throught all of my three inputs to check are they empty
var formInvalid = false;
$('#allInputs input').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty.');
$('#ChangePassword').modal({
backdrop: 'static',
keyboard: false // I need to prevent user from clicking ESC or something
})
}
}
But I get following error (check the image):
EDIT:
FULL CODE:
<div class="form-group">
<label for="UserPassword">Pw:</label>
#Html.TextBoxFor(model => model.PasswordHash, new { #class = "form-control custom-input", data_toggle = "modal", data_target = "#ChangePassword", ariaDescribedby = "basic-addon1" })
</div>
#*Modal for ChangePassword which is opening when user clicks on control above ^*#
<div id="ChangePassword" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Updating password</h4>
</div>
<div class="modal-body" id="allInputs">
#*Modal Old Password*#
<div class="form-group">
<label for="UserPassword">Old password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="Eldin123" name="oldPassword" id="OldPassword" data-toggle="modal">
</div>
#*Modal New Password*#
<div class="form-group">
<label for="UserPassword">New password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="" name="newPassword" id="NewPassword" data-toggle="modal">
</div>
#*Modal Repeat New Password*#
<div class="form-group">
<label for="UserPassword">Confirm new password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="" name="confirmPassword" id="ConfirmNewPassword" data-toggle="modal">
</div>
#*Modal - submit*#
<div class="confirm-login">
<button type="button" class="btn custom-btn-big" onclick="comparePasswords();">NEXT</button>
</div>
</div>
</div>
</div>
</div>#*end of Modal for ChangePassword*#
#*Confirm button*#
<div class="confirm-login">
<button class="btn custom-btn-big" data-target="#">SAVE ALL CHANGES</button>
</div>
</div>
</div>
</div> #*End of User / Administration*#
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
function fieldInvalid() {
var formInvalid = false;
$('#allInputs input').each(function () {
if ($(this).val() === '') {
formInvalid = true;
console.log(formInvalid);
}
});
}
function passwordsInvalid() {
var invalidPassword = true;
var oldPw = $("#OldPassword").val();
var newPw = $("#NewPassword").val();
var confirmNewPw = $("#ConfirmNewPassword").val();
if (oldPw != newPw) {
alert('Postojeći password nije ispravan.');
}
else if (oldPw != confirmNewPw) {
alert('Password koji ste unijeli se ne slaže.');
}
else {
invalidPassword = false;
}
return invalidPassword;
}
var comparePasswords = function () {
if (fieldInvalid()) {
alert('One or more fields is empty.');
}
else {
if (!passwordsInvalid()) {
$("#ChangePassword").modal('hide');
}
}
}
</script>
}
So when someone clicks on password input, modal will be opened, and from that modal after informations are there user should click on button "NEXT" and there is event onclick which is calling comparePasswords method.
You are missing bootstrap library file.
Order of the file should be
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Same Problem (missing bootstrap.js) http://jsfiddle.net/1aeur58f/676/
Problem resolved (by adding bootstrap.js) http://jsfiddle.net/1aeur58f/677/
Hope this will help you.

how to refresh and rebind the data from db in angularjs

hi all iam using angularjs ngrepeat to bind the datas into table.i have one add new button when i click bootstrap model popup open i fill the input details click submit means data will stored correctly but table couldn't not get the new data but once i reload the page data will show
my controller code
var refresh = function () {
$http.get('/ViewFacility').success(function (response) {
$scope.ViewFacilitys = response;
};
refresh();
My add new code:
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
refresh();
});
};
Html Code
<form name="profileform">
<div class="modal fade" id="myModal" role="dialog" ng-controller="IndexController">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="margin-top:135px">
<div class="modal-header">
<h4 class="modal-title ">Role Name</h4>
</div>
<div class="modal-body">
<h4>Name</h4>
<input type="text" name="RoleName" class="form-control" ng-model="Role.RoleName">
<span class="error" ng-show="profileform.FirstName.$invalid && profileform.FirstName.$dirty">Please enter a First Name</span>
<h4>Description</h4>
<input type="text" name="Description" class="form-control" ng-model="Role.Description">
<span class="error" ng-show="profileform.LastName.$invalid && profileform.LastName.$dirty">Please enter a Last Name</span>
<h4>IsActive</h4>
<input type="checkbox" name="IsActive" class="form-control checkbox" ng-model="Role.IsActive" style="margin-left:-47%" >
<span class="error" ng-show="profileform.Email.$invalid && profileform.Email.$dirty">Please enter a Email</span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="AddRole()" ng-disabled="profileform.$invalid">Submit</button>
<button class="btn btn-primary" data-dismiss="modal" ng-click="deselect()">Clear</button>
</div>
</div>
</div>
</div>
</form>
Just add the new item to the array.
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
$scope.ViewFacilitys.push($scope.Role);
});
};
You don't need to fetch all data each time you create a new item. Refresh must be called just one time.
For pagination you can code a simple function that send the number of page to the server:
$scope.changePage = function (page) {
$scope.get('/ViewFacility?page='+page)
.then(function (response) {
$scope.ViewFacilitys = response.data;
});
}
Try modifying your refresh function like so
var refresh = function () {
$http.get('/ViewFacility').success(function (response) { //assuming this only fetches the newly added one
$scope.ViewFacilitys.push(response);
};

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.....
}

Categories

Resources