How to create a copy text link? - html

I created a code and I want the visitor to be able to copy the BTC address <small type="text" id="copy-to-clipboard">{{ group.field_groupe_donation.value }}</small> by clicking on the fontawesome icon <button class="btn btn-default btn-xs" onclick="copyText()"><i class="fas fa-copy"></i></button>.
How to do this ?
(function($) {
function copyText() {
var text = document.getElementById("copy-to-clipboard");
text.select();
document.execCommand("copy");
alert("Copied the text: " + text.value);
}
})(jQuery);
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="message-donation text-justify">
<div>Si le contenu de ce groupe vous plait, vous pouvez faire un don à son l'auteur en Bitcoin (BTC).</div>
<div class="h3"><i class="fab fa-bitcoin fa-lg btc"></i> Adresse BTC :</div>
{{ content.field_groupe_donation }}
<small type="text" id="copy-to-clipboard">{{ group.field_groupe_donation.value }}</small>
<button class="btn btn-default btn-xs" onclick="copyText()"><i class="fas fa-copy"></i></button>
<div class="mt-3 text-center">
<b>Comment ça marche ?</b>
</div>
</div>
Here is the result :
It does not work.

After modifying your code, I propose to create the "copyText" function in this way.
function copyText() {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($("#copy-to-clipboard").text()).select();
document.execCommand("copy");
$temp.remove();
alert('Copied');
}
The instruction document.execCommand("copy"); allows you to copy all the elements of the DOM you have selected using the .select() function.

You can use the clipboard API for this. Please note that this requires your site to run in a secure context (https or localhost).
Example:
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('bar').addEventListener('click', () => {
if (window.isSecureContext && 'clipboard' in navigator) {
navigator.clipboard.writeText(document.getElementById('foo').textContent);
} else {
console.error(`Clipboard API requires secure context or your browser doesn't support clipboard API`);
}
})
})
<small id="foo">This text should be in your clipboard after clicking the copy button</small>
<br />
<button id="bar" type="button">copy</button>
<br />
<textarea placeholder="try pasting here after clicking copy button" cols="60" rows="3"></textarea>
As with most things, in 2020 you want to be using the browser API and not jQuery.

Related

Modal ajax.form validation ASP.NET MVC, error message not showing, modal not closing after succesful submit

i'm new to the ASP.net and i get easilly confused when jquery and Ajax get in the middle of a code.
I have a popup bootstrap Modal that show when i click on a button, the Modal contains an Ajax.form that allows me to create projects, i'm using HTML.validation to check if my form is filled correctly. I have two main problems :
When I enter valid informations in my form and i submit the form, the project is created succesfully but the Modal doesn't close automaticlly.
When i enter non-valid informations when i submit no message error apear, nonetheless when I close the modal and open it again, the errors apear.
I need your help to :
Close the modal once the submit form is valid.
Have the error message show in my modal form.
*This is a part of my main view :
enter code here
<!--validation script -->
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<!-- Button trigger modal -->
<div>
<div>
<a class="btn btn-red ms-auto my-auto h-50"
href="#Url.Action("createProject", "ProjectSelection")" title="Nouveau projet"
data-bs-toggle="modal" data-bs-target="#Modal_NewProject"
ajax-target-id="Body_NewProject" data-bs-loader="Loader_NewProject">
<i class="feather-16" data-feather="plus"></i>
Créer projet
</a>
</div>
</div>
<br />
<!-- Modal View -->
<div class="modal fade" id="Modal_NewProject" tabindex="-1"
aria-labelledby="Label_NewProject" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="Label_NewProject">
Créer un Projet</h5>
<button type="button" class="btn-close"
data-bs-dismiss="modal" aria-label="Close"></button>
</div>
#using (Ajax.BeginForm("createProjectPost",
"ProjectSelection", new AjaxOptions { HttpMethod = "POST",
UpdateTargetId = "Body_NewProject" }, new { id = "projectForm" }))
{
<div id="Body_NewProject">
<div class="spinner-border" role="status"
id="Loader_NewProject">
<span class="visually-hidden">Loading...</span>
</div>
<!-- partial view "createProject" -->
</div>
}
</div>
</div>
</div>
<!---->
*And this is my partial view that containts the elements of the form
<div class="modal-body" id="frmProject">
<div class="input-group mb-3" id="">
#Html.DropDownListFor(m => m.Project.Domain,
new SelectList(Model.Domains, "IdDomain", "Name"),"Selectionner un domaine",
new { #class = "w-100", #id = "DomainSelection" })
#Html.ValidationMessageFor(m => m.Project.Domain, null,
new { style = "color: red;" })
</div>
<div class="input-group mb-3 mb-3 " id="teamSelection">
#Html.DropDownListFor(m => m.Project.Teams,
new SelectList(Model.Teams.Select(teamElement => teamElement.Name).ToList()),
"Selectionner une équipe", new { #class = "w-100" })
#Html.ValidationMessageFor(m => m.Project.Teams, null,
new { style = "color: red;" })
</div>
<div class="form-floating mb-3">
<input class="form-control " data-val-required="Le champ Projet est requis."
id="Project.Name" name="Project.Name" type="text" value="">
<label for="Project.Name" class="">Nom du projet</label>
#Html.ValidationMessageFor(m => m.Project.Name, null,
new { style = "color: red;" })
</div>
</div>
<div class="modal-footer mb-0">
<div class="panel-footer">
<button class="btn btn-secondary" data-bs-dismiss="modal"
type="button">Annuler</button>
<button type="submit" form="projectForm"
class="btn btn-red">Valider</button>
<div class="col-xs-10" id="lblstatus"></div>
</div>
</div>
*This is my Controller code
public ActionResult createProject()
{
//initialization code
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
[HandleError]
public ActionResult createProjectPost(Project project)
{
#region Variable verification
if (!ModelState.IsValid)
{
Session["Error"] = true;
if (project.Domain == null)
{
Session["DomainError"] = true;
}
if (project.Teams == null)
{
Session["TeamError"] = true;
}
if (project.Name == null)
{
Session["NameError"] = true;
}
ViewData["project"] = "create";
//return View("ProjectSelectionPage");
return PartialView(project);
}
#endregion
#region Initialisation
//initilization code
#endregion
#region Check possible copy of the project
if (projectDB.Exist(project.Name))
{
//Check that this project doesn't exist in the database
//Create a session variable that will trigger an error message
Session["Error"] = true;
Session["NameCopy"] = true;
ViewData["project"] = "create";
return PartialView(project);
}
#endregion
#region Project to database and generate name
//Add the project to the database
#endregion
return PartialView();
}
It's been several days since i'm searching for an answer, i either missed one or didn't use it correctly.
enter image description here
Thank you

Show / Hide javascript function

I'm trying to show a div if the URL contains a parameter.
I've run my JS on Chrome Console and it works just fine, but when I publish it doesn't work.
What am I doing wrong?
HTML
<div class="alert alert-success" id="vendaPremium" style="display: none;">
<div class="container">
<div class="alert-icon">
<i class="material-icons">check</i>
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true"><i class="material-icons">clear</i></span>
</button>
<b>Uhulll! Você acaba de se tornar cliente Meu Marketing Premium. Em breve entraremos em contato. \o/</b>
</div>
</div>
JavaScript
function sucessoCompra() {
var alertaPagSeguro = window.location.href.split("?")[1];
if (alertaPagSeguro === 'sucessoPagSeguro') {
$('#vendaPremium').show();
} else {
$('#vendaPremium').hide();
}
}
window.onload = sucessoCompra();
This is how I would do it:
$(document).ready(function() {
sucessoCompra();
});
function sucessoCompra() {
const urlParams = new URLSearchParams(window.location.search);
var alertaPagSeguro = urlParams.get("query"); // Replace with name of your parameter
if (alertaPagSeguro == "sucessoPagSeguro") {
// Parameter equals string
$("#vendaPremium").show();
} else {
// Parameter does not equal string, or doesn't exist
$("#vendaPremium").hide();
}
}
Problem could be because the script is executed before the JQuery library has been processed. If that's the issue, simply insert the <script> element (of your main code) below the JQuery Library.
Otherwise, what's the URL to the published webpage? Using my example above would probably be more efficient, as URLSearchParams() is widely supported - not on Internet Explorer however, so you may need a fallback.

How to change ng-include inside firebase firestore function

When I click on continue button it checks clients ID in firestore database and if ID does'nt exist then $scope.filePath = "createClient.htm" is called. everything is working fine but when I call this piece of code inside firebase function nothing happens
Inside HTML
<div ng-include="filePath" class="ng-scope">
<div class="offset-1 offset-sm-2 col-11 col-sm-7">
<h2>Enter Client ID</h2>
<br>
<div class="form-group">
<label for="exampleInputEmail1">ID</label>
<input id="client_id" type="text" class="form-control" placeholder="Client ID">
</div>
<div class="float-right">
<button type="button" class="btn btn-danger">Cancel</button>
<button type="button" ng-click="searchClient()" class="btn btn-success">Continue</button>
</div>
</div>
</div>
Internal Script
<script>
$scope.searchClient = function()
{
//$scope.filePath = "createClient.htm"; it works here
var id= document.getElementById('client_id').value;
db.collection("clients") // db is firestore reference
.where("c_id","==",id)
.get()
.then(function(querySnapshot)
{
querySnapshot.forEach(function(doc)
{
if(!doc.exists)
{
console.log("Client Does'nt Exist");
$scope.filePath = "createClient.htm"; // but doesnt works here inside this firebase function
}
}
);
}
);
}
};
</script>
when console.log is shown and firebase function are fully executed then if I click on "Continue" Button again it works fine and content of createClient.htm is shown inside ng-include="filePath". why i need to click twice ?

Autofill on textbox (in Chrome) results in being prefilled without pushing enter

I have a very strange issue, that results in quite a lot of problems for our visitors.
On a normal textfield, Chrome (and other browsers) suggests strings to prefill. When you hover them and move the mouse away, they are not selected and written in the textbox.
However, in my setup, I have a weird case. When I hover my options, and then move the mouse it, it selects an item in the box. This results in an awful lot of "please enter an email" messages, while the user sees an e-mail on their screen.
See problem in this video:
https://www.youtube.com/watch?v=Vh2nb0_IR3Q
My markup for this particular e-mail:
<input type="text" name="Email" placeholder="E-mail" id="newUserEmail" class="email_input newinputtxt">
Does anyone have a hint? Because i am really lost...
EDIT:
Full ASP.NET MVC markup:
<asp:Content ID="Content1" ContentPlaceHolderID="plhMain" runat="server">
<h2>Indtast e-mail adresse</h2>
<div class="checkout__section checkout__section--login checkout_auth">
<div class="single_login">
<div id="newUserBox">
<div id="provideUserEmailBox">
<div class="email_auth">
<div>
<input type="text" name="Email" placeholder="E-mail" id="newUserEmail" class="email_input newinputtxt" />
</div>
<span class="red auth-error-text" style="display: none;" id="invalidEmailText">Der skal indtastes en gyldig e-mail</span>
<ul class="red_checkmarks" style="margin-top: 5px;">
<li>Vi bruger e-mail adressen til at sende en bekræftelse pa din ordre</li>
<li>Hvis du vil, kan du logge ind eller oprette en konto på næste side.</li>
</ul>
</div>
</div>
<div id="createNewUserBtnBox">
<input id="newUserBtn" type="button" class="button button--primary" value="Fortsæt" />
<span class="red auth-error-text" id="createNewUserErrorText"></span>
</div>
</div>
</div>
<div id="socialLoginList">
<button class="pfacebook" type="button" name="provider" value="facebook" title="Log ind med din Facebook konto">
Facebook
</button>
<button class="pgoogle" type="button" name="provider" value="google" title="Log ind med din Google konto">
Google
</button>
</div>
</div>
<script type="text/javascript">
$(function () {
$("#newUserEmail").keypress(function (event) {
if (event.keyCode == 13) {
event.preventDefault();
$("#newUserBtn").click();
}
});
var auth = CheckoutAuthorizationFlow({ LoginUserBox: "#loginWithUserBox", NewUserBox: "#newUserBox" });
auth.Init();
var facebookLogin = function () {
var loginUrl = '/login?returnurl=' + encodeURIComponent(document.location.href) + '&r=' + (new Date().toUTCString()) + '&provider=facebook';
//alert('facebook login');
document.location.href = loginUrl;
return;
};
var googleLogin = function () {
var loginUrl = '/login?returnurl=' + encodeURIComponent(document.location.href) + '&r=' + (new Date().toUTCString()) + '&provider=google';
document.location.href = loginUrl;
return;
};
$(".pfacebook").click(facebookLogin);
$(".pgoogle").click(googleLogin);
});
</script>
</asp:Content>
So my roommate, who has been working a bit with Wordpress a couple of years back, just came by my computer and said:
"Wrap it in a form tag!"
So I told him that was a horrible idea, and he said "try it".
And I did.
And it fucking worked.
So tl;dr -> wrap it in a form tag, and it works... I'll go cry.

popup with bootstrap

how can i create a popup with MVC bootstrap?
I have this code, when I click on "generate password" calls to a function (it´s in my controller Admin) and it returns me a string. How can i display the string in a popup window??
<div class="editor-field" title="User Password">
<a class="btn btn-primary btn-small" href="#"
onclick="location.href='#Url.Action("GeneratePsw", "Admin", null)'; return false;">
<i class="icon-lock icon-white"></i> Generate password
</a>
</div>
Since event listeners are better than click events, I'd probably do something like this:
<div class="editor-field" title="User Password">
<a id="pwd_gen" class="btn btn-primary btn-small" href="#">
<i class="icon-lock icon-white"></i> Generate password
</a>
</div>
$(function() { // document.ready shorthand
$('#pwd_gen').click(function() {
var myPwd = $(this).location.href='#Url.Action("GeneratePsw", "Admin", null);
alert(myPwd); // or however you want to handle it with Bootstrap
});
});
$(document).on("click", ".open-ShowPwdDialogUser", function () {
var pwd="";
$.get("#Url.Action("GeneratePsw", "Admin")",function(data){
pwd=data;
$(".modal-body #pwdUser").val(pwd);
$('#1').modal('show');
});
})