javascript code behind values - c#

I have the following JS code which shows/hides buttons (had to be done this way, and please don't say do it another way).
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandle);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandle);
function beginRequestHandle(sender, Args) {
document.getElementById("ltInstructions").style.visibility = "hidden";
document.getElementById("btnSubmit").style.visibility = "hidden";
document.getElementById("btnToExcel").style.visibility = "hidden";
}
function endRequestHandle(sender, Args) {
if(<%=resultsCount %> > 0)
{
document.getElementById("ltInstructions").style.visibility = "visible";
document.getElementById("btnSubmit").style.visibility = "visible";
document.getElementById("btnToExcel").style.visibility = "visible";
}
else
{
document.getElementById("results").innerHTML = "<br><b><center><font size=20>No results found, please try again.</b></font></center>";
}
}
The problem is <%=resultsCount %> which gets initialized to 0 in the code behind and then later updated in Timer_Tick method. The Js above always picks it up as 0.
How to make the JS pick it up as the correct value?

Use asp:hiddenfield instead and change its value in Timer_Tick, You will get updated value for it.
In HTML
<asp:HiddenField id="resultsCount" runat="server" Value="String" />
In Javascript
resultsCount = document.getElementById('<%= resultsCount.ClientID %>').value;

Try looking at the source of the webpage in your browser. You have to write the timer in JavaScript, because <%=resultsCount %> is evaluated once only and therefore, all the client sees is
if (0 > 0) {
...
}
You can implement a timer in JavaScript using the setInterval and clearInterval methods. Define a function update() that should be called whenever something needs to be updated and then do
var updateInterval
function update() {
if(condition) {
/* update stuff */
} else {
/* no more updates needed */
clearInterval(updateInterval) /* stop updating */
}
}
updateInterval = setInterval(update, 1000) /* call update() every 1000 ms, that is every second */

Related

pop up does not go for post back in asp.net

I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}

How To set Default Button for ENTER key

We are using Sharepoint 2007 In which on master page we have Asp Image button. We want to set this image button as default button for enter key press. We tried some ways but not getting success.
Turned out more complicated than I thought but possible nonetheless. First of all, make sure the ID of your control is static:
<asp:ImageButton runat="server" ID="MyImageButton" ClientIDMode="Static" ImageUrl="pic.gif" OnClick="ImageButtonClicked" />
Now what you need is the following JavaScript code in your .aspx or .master page:
<script type="text/javascript">
var DEFAULT_BUTTON_ID = "MyImageButton";
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// A fallback to window.onload, that will always work
window.addEventListener("load", HandleDefaultButton, false);
// If IE event model is used
} else if (document.attachEvent) {
// A fallback to window.onload, that will always work
window.attachEvent("onload", HandleDefaultButton);
}
function HandleDefaultButton() {
var inputs = document.getElementsByTagName("input");
//attach event for all inputs
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//maybe already got handler so add instead of override
if (document.addEventListener)
input.addEventListener("keypress", InputElement_KeyPressed, false);
else if (document.attachEvent)
input.attachEvent("onkeypress", InputElement_KeyPressed);
}
}
function InputElement_KeyPressed(evt) {
if (DEFAULT_BUTTON_ID && DEFAULT_BUTTON_ID.length > 0) {
//old IE event module
if (typeof evt == "undefined" || !evt)
evt = window.event;
var keyCode = evt.keyCode || evt.which;
if (keyCode === 13) {
var oButton = document.getElementById(DEFAULT_BUTTON_ID);
if (oButton) {
oButton.click();
return false;
} else {
alert("---DEBUG--- default button is defined but does not exist (" + DEFAULT_BUTTON_ID + ")");
}
}
}
return true;
}
</script>
You just need to define the real ID as the value of DEFAULT_BUTTON_ID and the code will automatically attach keypress event to all inputs (text, checkbox and radio) and when Enter is pressed, the button defined as default will get clicked.
As you're using SharePoint is means window.onload is already in use so we must add our own event not override it.
You can set the DefaultButton property to the id of the button you want to be default in the form tag.

assign value to javascript variable In C# CodeBehind

How can i assign value to javasctipt variable from code-behind (C#)?
<script type="text/javascript">
String.prototype.trim = function () { return this.replace(/^\s+|\s+$/, ''); };
function ConstantByCode(_Obj, _Div) {
var pl = new SOAPClientParameters();
_Obj.value = _Obj.value.trim();
pl.add("Code", _Obj.value);
pl.add("Group", _Obj.Grp);
alert(_Obj.Grp);
var _Value = SOAPClient.invoke("ConstantWS.asmx", "GetConstantByCode", pl, false, CallBackEvent);
if (_Value == null || _Obj.value == "" || _Obj.value == null || IsNumeric(_Obj.value) == false) {
_Obj.value = "";
_Div.innerHTML = "";
}
else {
_Div.innerHTML = _Value;
}
}
function CallBackEvent(r) {
}
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
BehindCode
txtCode.Attributes.Add("Grp", Me.ConstValue)
txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")
txtCode.Attributes.Add("onkeyup", "ConstantByCode(this," & DivTitle.ClientID & ");")
_obj.Grp has now value.
alert said : undefined
I see that you want to retrieve value of Grp that is a custom attribute. You need to use getAttribute function - so instead of _Obj.Grp, you need to use _Obj.getAttribute("Grp").
Also, I see that you are not enclosing client id in quotes from ode-behind. So instead of
txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")
you need to say
txtCode.Attributes.Add("onchange", "ConstantByCode(this,'" & DivTitle.ClientID & "');")
Note the single quote(') around the client id.
Further, ConstantByCode js function appears to be taking div element. Hence, you need to add line to it for converting from client id to actual DOM. i.e.
function ConstantByCode(_Obj, _Div) {
_Div = document.getElementById(_Div);
.... // rest of the code
Firstly you will need to have access to the value on the client. We can do this by storing the value in a hiddenfield or by adding an attribute to the control. It seems you wish to do this by using an attribute so lets do this first.
add the following to your page_load method so we have access to the C# value on the client.
protected void Page_Load(object sender, EventArgs e)
{
string requiredJSValue = "put your value here";
txtCode.Attributes.Add("CSCodeAttribute", requiredJSValue);
}
We then need to access this value through Javascript. Firstly we will need to get the client ID of the control as C# will set this value. Note. I am using Jquery to retrieve the control ID. This is not required, however I prefer it. Jquery is a framework for javascript and can be downloaded from www.jquery.com
function GetCSAttributeValue()
{
var csControlID = $('#<%= txtUOMCost.ClientID %>'); //Gets the control name.
var requiredJSValue = csControlID .attr("CSCodeAttribute"); //Value stored in variable.
}
I'm not 100% sure but I think you'll need a workaround to get this working. Because logically at the backend the javascript variable doesn't even exist. You can probably create a hidden field and make it a bridge between the javascript variable and code behind. Check this: http://forums.devx.com/showthread.php?t=164356
Try this:
1. Add a hidden field in you .aspx page:
<asp:HiddenField ID="hidden" runat="server" />
2. Change the value of this field in your code-behind:
protected void Page_Load(object sender, EventArgs e)
{
hidden.Value = "hello";
}
3. Write the following script to access the value and put it in any variable:
<script type="text/javascript">
if (document.getElementById("MainContent_hidden") != undefined) {
var hiddenVal = document.getElementById("MainContent_hidden").value;
}
else {
var hiddenVal = null;
}
</script>
WARNING: The third part is tricky. We are not using the same ID that we provided in the 1st step when we are calling the getElementById function. This is because asp.net changes this and the temporary workaround is to run the page once and view its source. Check the id of the hidden field and put it in step 3 inside the getElementById function. You can look for better alternatives but for now use this if you want. If you're struck at step 3, let me know.
I don'see how your question is related to the code...
But to set a value of a javascript value from serverside... well you can't, because server side code runs precisely in the server and way before the HTML goes to the client and javascript gets executed.
But what you can do is make your server side code generate a piece of javascript that holds your value.
<script type="text/javascript">
var x = <%= ServerSideMethod() %>;
</script>

jQuery highlighting with ASP:UpdatePanel

I'm currently working with the AJAX:UpdatePanelAnimationExtender and I've implemented it in code behind which is currently working perfectly but I've ran into a problem with using the UpdatePanelAnimationExtender and an ASP:Repeater. I've been messing around with different ways of implementing it but nothing has worked correctly...
I've tried to have it written in codebehind - inside itemBound (generates the code perfectly, is attached to the UPAE but of course is dropped on partial postback).
I've also attempted using it in the aspx which also posed a problem.
The repeater itself is creating a table of items (a cart) and I am attempting to highlight items that have changed when a postback happens (highlight qty if the qty changes, etc).
I've read that jquery has a much cleaner way of doing this and am attempting to go that direction.
edit:
I'm currently looking at
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
changedHighlight();
}
function EndRequestHandler(sender, args){
if (args.get_error() == undefined){ changedHighlight(); }
}
function changedHighlight() {
$(document).ready(function() {
$('span,input,option,select').live('change', function() { $(this).effect("highlight", {color: "#44EE22"}, 1500); });
});
}
I'd have to compare a stored value for it to the new posted value, which I'm working on right now. Also 'change' doesn't appear to work on asp:labels?
Ended up using a global var (eh..) due to the issue of postback with the UpdatePanel and DOM recreation every time (meaning not able to use $.data() or this.data()).
Will only highlight non-submit inputs and DOM elements that have an ID. (otherwise static asp:labels will continue to flash)
var oldVar = [];
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler)
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
function BeginRequestHandler(sender, args) {
$(document).ready(function() {
oldVar = [];
$('input,select,span').each(function() {
if (this.type != "submit" && this.id != '') oldVar[this.id] = getValue(this);
});
});
}
function EndRequestHandler(sender, args){
$(document).ready(function() {
$('input,select,span').each(function() {
if (this.type != "submit" && this.id != '')
{
if (oldVar[this.id] != getValue(this))
{
$(this).effect('highlight', {color: '#44EE22'}, 3000);
oldVar[this.id] = getValue(this);
}
}
});
});
}
function getValue(control){
if ('value' in control) return control.value;
else if('textContent' in control) return control.textContent;
else if('innerText' in control) return control.innerText;
}

how to run href="#var=something" before onclick function fires in javascript?

i'm using the below javascript to change an image on an aspx in asp.net c#
<script language="JavaScript" type="text/javascript">
var updateImageWhenHashChanges = function()
{
theImage = document.getElementById("ctl00_ContentPlaceHolder1_Image1a");
if(window.location.hash == "#size=2")
{
theImage.src = "<%# Eval("realfilename", "/files/l{0}") %>";
}
else if(window.location.hash == "#size=3")
{
theImage.src = "<%# Eval("realfilename", "/files/{0}") %>";
}
else if(window.location.hash == "#size=1")
{
theImage.src = "<%# Eval("fullthumbname", "/thumbnails/{0}") %>";
}
else
{
}
}
</script>
here's how i call it with a link
test
the problem is that it only does what i'm expecting on the SECOND click of the link, because it seems onclick fires before the href, so the first time i'm just placing the var and the 2nd time i'm actually getting what i want.
does anyone know how i can fix this? i'm trying to get the image to change on each click
Perhaps you can replace your href with javascript:void(0) and then handle the link's "natural" click behavior at the end of your onclick() script.
Have you tried a different event like onmouseup or onunload?
You should pass in the current anchor's href to the function call and then use that in your if statements, then return false so that the default behavior isn't used.
var updateImageWhenHashChanges = function(pChoice)
{
theImage = document.getElementById("ctl00_ContentPlaceHolder1_Image1a");
if(pChoice == "size2")
{
// more lines of picking and choosing... and finally:
return false;
and then in the anchor
test
It would also be much better if you could use your databinding to put the real href of the image into the href of the anchor so that if JavaScript wasn't enable the user would still end up being able to see the image in question. Then your function code would just be getting a handle to the image and setting the source to that inbound param.
What about something like this:
<script type="text/javascript">
var updateImageSize = function(imageType, imageID)
{
thisImage = document.getElementById(imageID);
switch(imageType)
{
case "thumb":
// change image src to the thumbnail's path
thisImage.src = "YourThumbNailPath";
case "medium":
// change image src to medium image path
thisImage.src = "YourMediumImagePath";
case "large":
// you get the picture
thisImage.src = "YourLargeImagePath";
default:
// whatever you want it to default to
thisImage.src = "YourThumbNailPath";
}
}
</script>
Then the implementation:
Update Image
Hope that helps.

Categories

Resources