Firebase Chat change reference with javascript - 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?

Related

how do i show password value when editing user details in MVC

I am working on a MVC core project. I have a view on which user can edit user details.
I have a input field of type password. When we are creating the user, it works fine in hiding the characters as one type in the textbox, but when I want to edit the user details, the password input does not show a value.
How do I enable an input of type password to show or have a value when editing and at the same time I want to include the show and hide password functionality on the input.
$(document).ready(function() {
let model = #Html.Raw(Json.Serialize(Model));
let passwordEl = $("#Password");
let showHide = $('#showHidePassword');
let showHideSpan = $('.icon');
if (model.InstitutionModel.InstitutionSMTP.Id == 0) {
passwordEl.attr('type', 'password');
} else if (model.InstitutionModel.InstitutionSMTP.Id > 0) {
passwordEl.attr('type', 'password');
}
showHide.click(function (e) {
let type = passwordEl.attr('type') === 'password' ? 'text' : 'password';
passwordEl.attr('type', type);
if (showHideSpan.hasClass('fa fa-eye')) {
showHideSpan.removeClass('fa fa-eye').addClass('fa fa-eye-slash');
} else {
showHideSpan.removeClass('fa fa-eye-slash').addClass('fa fa-eye')
}
})
})
<div class="form-group row ">
<label class="col-sm-3 col-form-label control-label" for="accountHolder">Password</label>
<div class="col-sm-9 input-group required_field">
<input asp-for="Password" id="Password" class="form-control border border-secondary" type="text" />
<div class="input-group-append">
<button class="btn btn-primary" type="button" id="showHidePassword" style="height:38px;">
<span class="fa fa-eye icon"></span>
</button>
</div>
<span asp-validation-for="Password" class="text-danger"></span>
</div>
</div>
`
You can use a button to change the type of the input,here is a demo:
html:
<input type="password" id="passwd" name="passwd">
<button type="button" id="eye" onclick="ShowPassword()">
<img src="https://cdn0.iconfinder.com/data/icons/feather/96/eye-16.png" alt="eye" />
</button>
js:
function ShowPassword() {
var s = document.getElementById("passwd");
s.type = s.type == "password" ? "text" : "password";
}
result:
Although, it is not recommended to directly show the user's password, instead you should ask user to enter old password and also have fields for new password.
In order to show value of input password field, you can set type attribute of input field to text.

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?

Modal pop up one time per user

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);
})
});

can't reset form input using ng-click

I want to reset input value using ng-click to add it's value to a $scope var then reset the input value
here is my html
<form ng-controller="questionsCTRL" class="ui large form" name="questionForm" ng-submit="addSurvey(questionForm)" novalidate>
<div class="ui segment" id="quest-answers">
<div class="two fields">
<div class="field">
<label>Add New Answer</label>
<div class="ui action input">
<input type="text" required name="answers" ng-model="answers"
ng-required="true" ng-minlength="5" placeholder="answer...">
<button type="button"
ng-click="addAnswer(questionForm.answers.$viewValue)"
ng-disabled="questionForm.answers.$invalid"
class="ui teal right labeled icon button">
<i class="add icon"></i>
Add
</button>
</div>
<small ng-show="questionForm.answers.$invalid" class="ui meta teal">Answers is required</small>
</div>
</div>
<div class="ui grid">
<div class="row">
<div class="eleven wide column">
<div class="field">
<div class="ui attached segment" ng-repeat="answer in answerGroup">
{{answer.text}}
<a href class="ui right floated link"><i class="circular delete icon"></i></a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
and this is controller content
UIASSIGN1.controller('questionsCTRL', function($scope , $rootScope , $state, $stateParams , $http ) {
// #dummy controller
$rootScope.sectorName = 'Questions';
var _SID = $stateParams.id;
$scope.answerGroup = [];
$http.get("api/survey/survey.json")
.then(function(response) {
var surveyArray = response.data;
$scope.surveyArray = [];
for (var i = 0; i < surveyArray.length; i++) {
var thisItem = surveyArray[i];
var thisElm = {name:thisItem.name,value:parseInt(thisItem._id)};
$scope.surveyArray.push(thisElm)
}
});
$scope.addAnswer = function(answer){
var inArray = {
text : answer
};
$scope.answerGroup.push(inArray);
$scope.questionForm.answers = {};
}
});
this ng-click adds value to $scope.userGroups but it doesn't reset the form input value only resets the $scope.questionForm.answers value to {}
As I mentioned in the comments the value of $scope.answer is mapped to this element:
<input type="text" required name="answers" ng-model="answers"
ng-required="true" ng-minlength="5" placeholder="answer...">
The ng-model="answers" means to define a variable called answers in the scope. Then in angular you can access it with $scope.answers, that is why:
$scope.answers = "";
Will reset the input element.
You could do it like this. Define the answer on the scope
$scope.theAnswer = '';
Set this as your ngModel for the input field:
ng-model="theAnswer"
Simplify your ng-click like this and add the answer to the array directly in the controller and then cleanup the answer:
ng-click="addAnswer()"
$scope.addAnswer = function(){
var inArray = {
text : $scope.theAnswer
};
$scope.answerGroup.push(inArray);
$scope.theAnswer = '';
}

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