Copy text to clipboard using Zero Clipboard in asp.net - c#

I am trying to use Zero *Clipboard* to copy text from Textbox to Clipboard when client clicks a Button. I am trying this for many days but no luck to make this work.
In Scenario, i have one Textbox which render data from the Database. I have one Button which when client clicks should copy text of the Textbox. I have tried following but its not working.
Some help will be appreciated.
<script type="text/javascript" src="/Scripts/ZeroClipboard.js"></script>
<script type="text/javascript">
ZeroClipboard.setMoviePath('/Scripts/ZeroClipboard.swf');
</script>
<script>
function test() {
ZeroClipboard.setMoviePath('/Scripts/ZeroClipboard.swf');
//create client
var clip = new ZeroClipboard.Client();
//event
clip.addEventListener('mousedown', function () {
clip.setText(document.getElementById('TextBox2').value);
});
clip.addEventListener('complete', function (client, text) {
alert('copied: ' + text);
});
//glue it to the button
clip.glue('d_clip_button');
}
</script>
<asp:TextBox ID="TextBox2" runat="server" BorderStyle="None" Enabled="False" Font-Size="Medium" ForeColor="Black" Width="213px"></asp:TextBox>
<asp:Button ID="d_clip_button" runat="server" Text="Copy" OnClientClick="javascript:test();" />

<html>
<body>
<button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">
Copy to Clipboard</button>
<script src="ZeroClipboard.js"></script>
<script src="main.js"></script>
</body>
</html>
//In Main.js file
// main.js
var clip = new ZeroClipboard( document.getElementById("copy-button"), {
moviePath: "/path/to/ZeroClipboard.swf"
} );
clip.on( 'load', function(client) {
// alert( "movie is loaded" );
} );
clip.on( 'complete', function(client, args) {
this.style.display = 'none'; // "this" is the element that was clicked
alert("Copied text to clipboard: " + args.text );
} );
clip.on( 'mouseover', function(client) {
// alert("mouse over");
} );
clip.on( 'mouseout', function(client) {
// alert("mouse out");
} );
clip.on( 'mousedown', function(client) {
// alert("mouse down");
} );
clip.on( 'mouseup', function(client) {
// alert("mouse up");
} );

<html>
<body>
<script type="text/javascript" src="ZeroClipboard.js"></script>
<div id="d_clip_button" style="border:1px solid black; padding:20px;">Copy To Clipboard</div>
<script language="JavaScript">
var clip = new ZeroClipboard.Client();
var myTextToCopy = "Hi, this is the text to copy!";
clip.setText( myTextToCopy );
clip.glue( 'd_clip_button' );
</script>
</body>
</html>

First of all, you're trying to pick element by wrong id. Since you use webforms, correct way is:
getElementById('<%=TextBox2.ClientID%>')
Also, following unobtrusive js style good solution might look like:
$().ready(function () {
ZeroClipboard.setDefaults({ moviePath: "/Scripts/ZeroClipboard.swf" });
var clip = new ZeroClipboard(document.getElementById('YourButtonId')); //or '<%=YourButton.ClientID%>' if you use asp.net button
clip.on('complete', function (client, args) {
alert("Copied text to clipboard: " + args.text);
});
});
Also your button should have data attribute data-clipboard-target(actually there're three ways to do it). Setting data-attributes to webforms control is tricky, so you might want to avoid using asp.net button here and do it like:
<input type="button" value="clickme" id="YourButtonId" data-clipboard-target="<%=TextBox2.ClientID %>"/>
Enjoy!

Related

Why do `JQuery` tabs lose styling after a button click

I am using JQuery tabs in my Asp.Net/C# app.
I am modelling my approach after this article. The JQuery is outside of my
<asp:UpdatePanel ID="UpdatePanel1"...></asp:UpdatePanel>
wrapper while the html components are inside.
Whenever I click a button, my tabs completely lose their CSS styling and I see all of the tab contents, rather than just the
<div id="current-tab">
for that tab.
Why is this happening and how do I fix it?
My guess is that its related to post-back or the update panel somehow, but I am not sure why the added C# code under page_load doesn't keep the selected tab current on post-back when the button is fired.
ASPX
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
...
</script>
....
<table>
<tr>
<td style="padding: 5px;">
<div id="tabs">
<ul>
<li>Tier 1</li>
<li>Tier 2</li>
<li>Tier 3</li>
<li>Tier 4</li>
</ul>
<div class="tab-content">
<div id="tab-1">
...
</div>
<div id="tab-2">
...
</div>
<div id="tab-3">
...
</div>
<div id="tab-4">
...
</div>
</div>
</div>
<asp:HiddenField ID="selected_tab" runat="server" />
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
...
selected_tab.Value = Request.Form[selected_tab.UniqueID];
...
}
You are right, it has something to do with a Partial PostBack. So in order for jquery functions to work again you need to rebind it after the Partial PostBack is done.
<script type="text/javascript">
$(document).ready(function () {
buildTabs();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
buildTabs();
});
function buildTabs() {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
}
</script>
But the selected tab is a different story. You also need to store the active tab somewhere and re-apply it after the partial PostBack is done. See this answer for details.
But basically you need to store the active tab ID in SessionStorage, cookie or Hiddden input and re-apply it in prm.add_endRequest(function () {

Print Preview of gridview is not center allign

I am trying to print one gridview . For that I gave a button and on button click I call javascript for printing tha grid.
function doPrint() {
var prtContent = document.getElementById('<%= grdHistoricalData.ClientID %>');
prtContent.border = 0; //set no border here
var WinPrint = window.open('', '', 'left=50,top=100,border=1px,width=1000,textAlign=center,height=1000,toolbar=0,scrollbars=1,status=0,resizable=1');
WinPrint.document.write(prtContent.outerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
This code is working fine but only thing is that print preview of gridview data is displaying left align.Normally Girdview Data is showing center align but when we print data shows in left align.
Gridview normal appearance
Print Preview of Gridview
Please help to do center align in print preview of Gridview.
There are several solutions I use in different circumstances.
1) external file. Load a small file to a iframe and call for data from parent.
<!--print.html -->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Printer version</title>
<script type="text/javascript">
window.onload = function () {
var a = this.parent.getContent();
document.body.innerHTML = a;
}
function printMe() {
window.print();
}
</script>
<link href="/Styles/print.css" media="print" rel="stylesheet" />
</head>
<body>
</body>
</html>
Parent document.
<div id="divPrint" style="display:none;">
<div class="popup">
<div style="overflow:hidden;">Printer Version
<div style="float:right;">
<input type="button" ID="btnPrnClose" value="X" onclick="return closePrint()" />
</div>
</div>
<iframe id="frPrint" style="width:100%;"></iframe>
</div>
</div>
</div>
<script type="text/javascript">
function getContent() {
return '<div>' +
'<div class="right no-print" onclick="printMe();" style="cursor: pointer;" title="Print"> \
<img alt="Print" src="/images/printer.png" /></div>' + document.getElementById('gvOuterContainer').innerHTML+ '</div>';
}
function closePrint() {
document.getElementById('divPrint').style.display = 'none';
}
function PrintMessage() {
document.getElementById('divPrint').style.display = '';
document.getElementById('frPrint').src = "print.html?a=" + Math.random();//force no-cache
return false;
}
</script>
2) Print from the page.
<style type="text/css" media="print">
*
{
border: none!important;
}
.noprint,.popup
{
display: none!important;
}
#scrollContainer
{
width: auto!important;
}
.pop-show
{
display: table!important;
left: 0;
margin-left: 0;
top: 0;
width: 100%!important;
z-index: 100;
}
/* and so on */
</style>
Details may differ.
Finally got answer , I need to set gridview property that resolve this issue
<asp:TemplateField ItemStyle-HorizontalAlign="Center">

Save the <LI> Class value on Site.master postback event

I wanted to change class of <LI> on click, which I managed to do with jquery (I'm Newbie in jquery)
The Code:
<script type='text/javascript'>
$(function () {
$('#Mymenu li').click(function () {
$('li.active').removeClass('active');
$(this).addClass('active');
});
});
</script>
It's work Perfectly. That Jquery code above removes class of an li and assign it to other, but once redirect/postback occurs its lost the value and back to the default value.
any Idea thanks
You can store value of currently selected li in cookie,localStorage or window hash and retrive the value on page reload.
check out window hash example
<script type="text/javascript">
$(function () {
$('li.active').click(function () {
//tweak this line
window.location.hash = $(this).attr('id');
$("li.active").removeClass("active")
$(this).addClass('active');
});
var hash = window.location.hash;
$("#"+hash).removeClass("active")
$("#"+hash).addClass('active');
});
</script>
Update
Check out the complete example
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function () {
$('li').click(function () {
//tweak this line
window.location.hash = $(this).index();
$("li.active").removeClass("active")
$(this).addClass('active');
});
var suffix = window.location.hash.match(/\d+/);
$("li:eq(" + suffix + ")").removeClass("active")
$("li:eq(" + suffix + ")").addClass('active');
});
</script>
<style>
.active {
color: red;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul>
<li>A
</li>
<li>B
</li>
<li>C </li>
<li>D
</li>
</ul>
</div>
</form>
</body>
</html>
Thanks to all who comments to my question, I got the better solution of this issue base on this site:
ASP.NET C# With list navigation how to set id=“current” on active navigation page?
Based on the my researched I need to set it manually in the Page_Load event:
here the code
protected void Page_Load(object sender, EventArgs e)
{
SetCurrentPage();
}
private void SetCurrentPage()
{
var pageName = GetPageName();
switch (pageName)
{
case "home.aspx":
HomeLink.Attributes["class"] = "current";
break;
case "Calendar.aspx":
CalendarLink.Attributes["class"] = "current";
break;
case "Bill.aspx":
BillLink.Attributes["class"] = "current";
break;
}
}
private string GetPageName()
{
return Request.Url.ToString().Split('/').Last();
}
it's working perfectly right now.

Javascript function is not working on asp:button Click event, where a test alert function works.!

I am trying to create an alert as described in this site http://needim.github.com/noty/
and here is the code
<head runat="server">
<title>Test</title>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/noty/jquery.noty.js"></script>
<script type="text/javascript" src="js/noty/layouts/top.js"></script>
<link rel="stylesheet" type="text/css" href="buttons.css" />
<script type="text/javascript" src="js/noty/themes/default.js"></script>
</head>
<body>
<div class="container">
<div id="customContainer">
</div>
</div>
<script type="text/javascript">
function generate(type, layout) {
var n = noty({
theme: 'defaultTheme',
text: 'Do you want to continue?',
buttons: [
{
addClass: 'btn btn-primary',
text: 'Ok',
onClick: function ($noty) {
// this = button element
// $noty = $noty element
$noty.close();
noty(
{
text: 'Record deleted !',
type: 'success',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(true); },
onClose: function () { },
afterClose: function () { }
}
});
}
},
{
addClass: 'btn btn-danger',
text: 'Cancel',
onClick: function ($noty) {
$noty.close();
noty(
{
text: 'Record not deleted !',
type: 'warning',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(false); },
onClose: function () { },
afterClose: function () { }
}
});
}
}
]
});
}
function TakeValue(result) {
if (result == true) {
document.getElementById("Hidden1").value = "true";
alert(document.getElementById("Hidden1").value);
} else {
document.getElementById("Hidden1").value = "false";
alert(document.getElementById("Hidden1").value);
}
}
function generateAll() {
generate('information', 'top');
}
</script>
<form id="form" runat="server">
<input id="Hidden1" type="hidden" value="false"/>
<asp:Button ID="Button2" runat="server" Text="Press" OnClientClick="return generateAll();" />
<input id="Button1" type="button" value="button" onclick="return generateAll();" />
</form>
</body>
I have placed two buttons ,one is HTML button while the other is of asp:Button,
The whole scenario just works fine when I use the HTML button ,but the page is not displaying the similar behavior in case of asp:Button click, I have placed a test function in JavaScript to test the OnClientClick event of the asp:Button and that worked fine,but I don't know why this alert is not getting called, I think there is some problem with the Noty JS.
Kindly give feed back
thanks.
As jbabey said in the comments:
an asp:button will cause a postback when clicked by default. you need to return false from the onclientclick, right now you are returning undefined since generateAll has no return.
Since you're using jQuery, I'd go one step further and not directly set the click attribute. Instead, set it using jQuery:
<script>
$(document).ready(function() {
$('#Button1').click(generateAll);
});
...
function generateAll(e) {
generate('information', 'top');
// This will prevent the default action of submitting the form.
e.preventDefault();
}
</script>
Could you please add UseSubmitBehavior="false" attribute to the asp:button.
<asp:Button ID="Button2" runat="server" Text="Press" UseSubmitBehavior="false" OnClientClick="return generateAll();" />
I hope this will resolve your issue. Please let me know whether it helped you or not.

Is there a way to send text to an aspcontrol via jquery

Is there a way to send data to an aspcontrol say a label called label1? Via jquery?
I know jquery only likes html but is there a way to just send the raw text to an asp control using a similar method below:
<script type="text/javascript">
$(function () {
$('button').click(function () {
$(document).ready(function () {
var x = $('textarea').val();
$('textarea').val('');
var label = $("#<%= Label1.ClientID %>");
var newdiv = $("<div></div>").html(x).attr('id', 'test');
$('#test1').append(newdiv);
var serializer = new XMLSerializer();
label.text(serializer.serializeToString(newdiv));
return false;
});
});
});
</script>
I think the bigger issue is asp.net changes the id and trying to get that in the code isn't that easy.
Can you use the name attribute? If so you can just look for the name attribute containing your name using the jquery selector '[ name *="YourName"]'
EDIT: I meant to add firebug is a great help for examining page elements and figuring exactly what you can use (Ex: asp.net adds a name attribute to a button by default) and whats going on (like your return false failing) then tweaking your jquery from the watch window.
Sample asp.net form content:
<p>
<asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" /></p>
<p>
<asp:Label ID="Label1" name="Label1" runat="server" Text="Label"></asp:Label>
</p>
<div id="test1"></div>
jquery:
$(function () {
$('[name*= "Button1"]').click(function () {
var x = $('[name*= "TextBox1"]').val();
var newdiv = $("<div></div>").html(x).attr('id', 'test');
$('#test1').append(newdiv);
$('[name*= "Label1"]').text($('#test1').html());
$('[name*= "TextBox1"]').val('');
return false;
});
});
Here's how to do it without jQuery:
<%# Page Inherits="System.Web.UI.Page" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
<script type="text/javascript" src="App_Resources/JavaScript/jquery-1.4.4.min.js"></script>
</head>
<body>
<form runat="server">
<asp:Label ID="testLabel" runat="server" Text="test" />
<script type="text/javascript">
$(document).ready(function ()
{
var label = document.getElementById("<%= testLabel.ClientID %>");
var div = document.createElement("div");
div.innerText = "content";
label.innerText = div.outerHTML;
});
</script>
</form>
</body>
</html>

Categories

Resources