This question is related to: Hide div on clientside click
The issue I am having is that after postback event from asp.net happens onClick any clientside changes made reset how can I keep the client side changes I am making.
Second question how can I get a variable from code behind and pass it into my javascript to perform a comparison.
Html:
<div runat="server" id="someDiv1" enableviewstate="true" >
<asp:LinkButton OnClientClick="Show_Hide_Display()"
ID="lbtnDiv1"
runat="server"
CausesValidation="true"
OnClick="lbtn_onClickServer">
</asp:LinkButton>
</div>
<div runat="server" class="tick" id="div2" style="display:none;" enableviewstate="true">
</div>
Javascript:
<script type="text/javascript">
function Show_Hide_Display() {
var div1 = document.getElementById("<%=someDiv1.ClientID%>");
var div2 = document.getElementById("<%=div2.ClientID %>");
if (div1.style.display == "" || div1.style.display == "block") {
div1.style.display = "none";
div2.style.display = "block";
}
else {
div1.style.display = "block";
div2.style.display = "none";
}
}
</script>
The OnClick event causes a postback like it should, on this occassion it checks if users, chosen username is available.
If it is available show a tick, if it isn't error.
I got the error working and am trying to program the tick on client side.
So OnClientClick I am able to toggle between some text and a tick. So I need to:
Get the bool result from code behind
After postback keep tick (if username is available)
I am almost there but can't quite figure the last two points out.
If you are using an UpdatePanel in your page, and assuming that div which you are trying to toggle is outside the control, you can always inject javascript on a partial postback:
Like for e.g. on your button's click event which executes on a partial postback make a call to ScriptManager.RegisterClientScriptBlock() --> How to retain script block on a partial postback?
Alternatively, you can append an end request handler. This is some javascript which should run after the partial postback. --> ASP.NET Register Script After Partial Page Postback (UpdatePanel)
The answer for the both questions lies of checking the boolean value send from the code behind.
1-----.in code-behind c#
protected void Page_Load(object sender, System.EventArgs e)
{
var linkbtn = (Button)Page.FindControl("lbtnDiv1");
linkbtn .Attributes.Add("onClick", "Show_Hide_Display('" + parameter+ "')");
}
2------- change your javascript
function Show_Hide_Display(parameter)
{
if( paramater=='true')
{
----your logic---
}
else
{
----your logic
}
}
Related
I'm trying to determine the client window size on pageload, to use in creating a bitmap using c#. From reading on SO and elsewhere, I know that one method would be to:
Write a Javascript function to get the relevant values;
Store these in hidden fields;
Read the value using the code behind (c#) and then do stuff with it.
However, I'm getting tripped up by the execution sequence that runs code behind BEFORE any Javascript, even though I've set <body onload... to get and set the relevant values. (see below)
I know the rest of my code works, because, when I execute, the page shows the word "by" and the button. Then, after I have clicked the button and the page reloads, it can now suddenly read the two hidden values.
My question is, how can I get my c# Page_Load code to get those two hidden values from the client side, before it executes the rest of my code, and without the need for user action like clicking a button?
My page:
<body onload="getScreenSize()">
<form id="form1" runat="server">
<input type="hidden" name="hiddenW" ID="hiddenW" runat="server" />
<input type="hidden" name="hiddenH" ID="hiddenH" runat="server" />
<script>
function getScreenSize() {
var myW = document.getElementById("hiddenW");
myW.value = window.innerWidth;
var myH = document.getElementById("hiddenH");
myH.value = window.innerHeight;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(hiddenW.Value+" by " +hiddenH.Value);
}
}
On first run (when I need those values), it shows
and after I click the button, it proves the Javascript works:
The question then, is how do I get those values before the rest of my Page_Load code runs, so that I can go straight into generating and displaying my image?
You cannot get the client window size before the C# Page_Load() executes because the page is rendered to the client after the C# code execution is complete.
The window size may change during page load, hence you have to get the window size only after page load is complete.
Solution:
You can use ajax to send the values to the back-end, after the page has loaded completely.
OR
You can cause a post-back using java-script after you get the correct value, this way:
JQuery:
$(function() {
var width = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var height = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
$('#hdn_width').val(width);
$('#hdn_height').val(height);
$('#your_form').submit();
});
C#:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// Use hdn_width and hdn_height here
}
}
catch (Exception ex)
{
}
}
Use the IsPostBack property
This would solve your problem
For Example
if(!Page.IsPostBack)
{
//Control Initialization
//Your code goes here
}
I used a timer to postback once and two none-displayed textboxes to store the window-values width and height. the textboxes are filled with a javascript:
document.getElementById('<%=TxWd.ClientID %>').value = window.innerWidth;
document.getElementById('<%=TxHt.ClientID %>').value = window.innerHeight;
In code behind (VB.NET):
Protected Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Session("seswidth") = Val(TxWd.Text)
Session("sesheigth") = Val(TxHt.Text)
Timer1.Enabled = False
End Sub
i have hiddentfield whose value is changing on javascript.
I just wanted to fire serverside event valuechanged event of hiddenfield when its value changed from javascript.
I tried with :
__doPostBack('hfLatitude', 'ValueChanged');
But giving me error :
Microsoft JScript runtime error: '__doPostBack' is undefined
Is there any other alternative for this?
Please help me.
In javascript, changes in value to hidden elements don't automatically fire the "onchange" event. So you have to manually trigger your code that is already executing on postback using "GetPostBackEventReference".
So, with a classic javascript approach, your code should look something like in the example below.
In your aspx/ascx file:
<asp:HiddenField runat="server" ID="hID" OnValueChanged="hID_ValueChanged" Value="Old Value" />
<asp:Literal runat="server" ID="litMessage"></asp:Literal>
<asp:Button runat="server" ID="btnClientChage" Text="Change hidden value" OnClientClick="ChangeValue(); return false;" />
<script language="javascript" type="text/javascript">
function ChangeValue()
{
document.getElementById("<%=hID.ClientID%>").value = "New Value";
// you have to add the line below, because the last line of the js code at the bottom doesn't work
fValueChanged();
}
function fValueChanged()
{
<%=this.Page.GetPostBackEventReference(hID, "")%>;
}
// the line below doesn't work, this is why you need to manually trigger the fValueChanged methiod
// document.getElementById("<%=hID.ClientID%>").onchange = fValueChanged;
</script>
In your cs file:
protected void hID_ValueChanged(object sender, EventArgs e)
{
litMessage.Text = #"Changed to '" + hID.Value + #"'";
}
Quick and Dirty:
Simply put a asp button on form. Set it display:none.
<asp:Button id="xyx" runat="server" style="display:none" OnClick="xyx_Click" />
On its click event call any server side event.
protected void xyx_Click(o,e)
{
//you server side statements
}
To call its from JS use as below:
<script>
function myserverside_call()
{
var o = document.getElementById('<%=xyx.ClientID%>');
o.click();
}
function anyotherjsfunc()
{
//some statements
myserverside_call();
}
</script>
First way is to use HiddenField.ValueChanged Event.
If you want to also watch this varible in Client Side just use this:
$('#hidden_input').change(function() {
alert('value changed');
});
Second way is to assign value to Varible:
$('#hidden_input').val('new_value').trigger('change');
I am having a user control file without its codebehind file in dotnentnuke.
In which i have put a form in which i have one textbox and one Linkbutton.
I want to pass that textbox's value when i press the button as querystring to access it in another page.
For that i have written following code but it does not work.
<asp:TextBox ID="txtemail" runat="server" class="txtbox" placeholder="Enter Email Here"></asp:TextBox>
<asp:LinkButton ID="LinkButton1" class="lbsubscrb" runat="server"
PostBackUrl="~/Portals/_default/Skins/Gravity/Dummy.aspx?add=<% txtemail.Text %>"
ForeColor="White">SUBSCRIBE</asp:LinkButton>
All answers are appreciated...
It sounds like you really just need your own custom module, instead of trying to take an existing module, without the source code, and make it do something completely different?
That being said, if you really want to take that existing module and make it do that, jQuery is likely going to be your method of choice.
Basically you wan to hijack the click event for the button and send it elsewhere, something along the lines of the following code. I actually wrote most of this last night for another module I was working on (newsletter subscriptions, by the way) but have removed some of my logic to make it simpler for what you are trying to do
EDIT: replaced the txtbox class below to match your textbox's class
<script language="javascript" type="text/javascript">
/*globals jQuery, window, Sys */
(function ($, Sys) {
$(document).ready(function () {
var originalHref = $('.lbsubscrb a').attr('href');
$('.lbsubscrb a').removeAttr("href");
$('.txtbox').focus(function () {
if($('.txtbox').val().indexOf('#')<1)
$('.txtbox').val('');
});
$('.txtbox').bind("keypress", function (e) {
if (e.keyCode == 13) {
$('.lbsubscrb a').click();
}
});
$('.lbsubscrb a').click(function () {
//check if they hit enter in the textbox and submit the form
if (validateEmail($('.txtbox').val())) {
//
//TODO: Add your jquery for the redirect call here.
//
//uncomment this line to actually use the original submit functionality
//eval(originalHref.replace('javascript:', ''));
//if postback is wanted uncomment next line
//$('.lbsubscrb a').removeAttr("href");
} else {
alert('something wrong with your email');
}
});
});
}(jQuery, window.Sys));
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
</script>
I have a Image Button declared as,
<div>
<asp:ImageButton ID="btnDoWork" runat="server" ImageUrl="/_LAYOUTS/1033/IMAGES/row.png" ValidationGroup="Page" />
</div>
<div>
<asp:RequiredFieldValidator runat="server" ID="reqName" ControlToValidate="txtEmail" ValidationGroup="Page" ErrorMessage="enter a email" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationExpression="^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$" ControlToValidate="txtEmail" ValidationGroup="Page" ErrorMessage="enter a email" />
</div>
within a update panel,
now in code behind I am doing something like this,
btnDoWork = (ImageButton)this.control.FindControl("btnDoWork"); //this code is in childcontrols method
btnDoWork.Click += new ImageClickEventHandler(btnDoWork_Click);
then
protected void btnDoWork_Click(object sender, ImageClickEventArgs e)
{
//Process a bit of code and at end,
this.Page.Unload += new EventHandler(Page_Unload_MessageBox);
and then in button click event,
public static void Page_Unload_Page_Unload_MessageBox(object sender, EventArgs e)
{
System.Globalization.CultureInfo _culture = Thread.CurrentThread.CurrentUICulture;
StringBuilder sb = new StringBuilder();
sb.Append("<script language=\"javascript\">");
sb.Append("$('body').append(\"<div id='M'><span id='text'>" +
SPUtility.GetLocalizedString("$Resources:abc", "def", (uint)_culture.LCID) +
"</span><br/><div id='BB' onclick='return BB();'><a href='' onclick='return BB();'>" +
SPUtility.GetLocalizedString("$Resources:OK", "def", (uint)_culture.LCID) +
"</a></div></div>\");");
sb.Append("function BB() { $('#M').remove(); $('#E').remove(); return false; }");
sb.Append("function dM(){ var browser = navigator.appName; if (browser == 'Netscape') { $('#M').css({ 'top': '5%' }, 500); } }");
sb.Append("</script>");
// Write the JavaScript to the end of the response stream.
HttpContext.Current.Response.Write(sb.ToString());
Now if I put email address I get error while when it tries to Response.Write I think, I wonder what alternative is there, e.g. can I use triggers in update panel or any other event or something..
here's the error I am getting now,
Note: I changed all variable names so don't get confused if something doesn't match
The message is very clear, you can not add this command HttpContext.Current.Response.Write on update panel, and that because can not know how to handle it, because the update panel is return a struct that is used by the javascript to redraw some part of the page.
The solution is to add a literal control inside the UpdatePanel, in the place you wish to add the extra html code, and write that control the render as:
txtLiteralID.Text = sb.ToString();
How ever, here you have a diferent situation than the normal, you won to render and run a script.
The main problem is how to trigger the script to run. The only way is to use the UpdatePanel handler that is this standard code:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel run the code.
UnloadMsgBox();
}
</script>
Now on the EndRequest you need to call your script, where it may all read exist in your code as:
function UnloadMsgBox()
{
// render your code of the javascript.
$('body').append(\"<div id='M'><span id='text'></span><br/><div id='BB' onclick='return BB();'><a href='' onclick='return BB();'></a></div></div>\");
function BB() { $('#M').remove(); $('#E').remove(); return false; }"
function dM(){ var browser = navigator.appName; if (browser == 'Netscape') { $('#M').css({ 'top': '5%' }, 500); } }"
}
and not need to render it on UpdatePanel.
To summarize:
On the update panel you can not use the Response.Write to render something but a literal control, that renders inside him.
On the update panel you can not render javascript code and expect to run, to run a javascript code you need to use the EndRequest handler that comes with the UpdatePanel.
MS Ajax calls perform full page rendering, calculate the diff from the original, send the diff to the client, and magically merge the diff in the browser.
If you just send javascript as response, it's something the framework does not expect and it throws the message.
See a previous answer on how to invoke javascript from an UpdatePanel.
I am still reasonably new to this and have tried to find an answer, so hopefully I am not repeating this.
I am using ASP.NET and have a checkbox control that brings up a popup box when it's changed, using the onCheckedChanged method. This popup box has some info in it and a 'Close' button which successfully closes the popup.
What I want is to prevent the popup appearing if the checkbox is being unchecked. I currently have the onCheckedChanged calling a code behind method which cancels the extender call if the control is not checked, but the popup quickly appears before it is closed. How can I prevent it this?
This is the appropriate page code:
<div class="row" id="divDDMandate" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:CheckBox ID="chkDDMandate" Width="20px" Visible="true" runat="server" AutoPostBack="true"
OnCheckedChanged="clientchkDDMandateChanged(this);" on />
<asp:Literal ID="ltlDDMandate" runat="server">Direct Debit Mandate (by post)</asp:Literal>
<asp:PopupControlExtender ID="chkDDMandate_PopupControlExtender" runat="server"
DynamicServicePath="" Enabled="true" PopupControlID="PanelDDMandateDownload"
TargetControlID="chkDDMandate"
Position="Bottom" OffsetX="-20" OffsetY="10" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
...and this is my code behind method:
protected void chkDDMandateChanged(object sender, EventArgs e)
{
//Cancel the panel if unchecking
if ((!chkDDMandate.Checked) && chkDDMandate_PopupControlExtender.Enabled)
{
chkDDMandate_PopupControlExtender.Cancel();
}
}
I would be grateful for any help.
Cheers
Remove AutoPostBack="true" from the chkDDMandate checkbox and add script below after the ScriptManager control:
<script type="text/javascript">
function pageLoad() {
var extender = $find("<%= chkDDMandate_PopupControlExtender.ClientID %>");
extender.remove_showing(onPopupShowing);
extender.add_showing(onPopupShowing);
}
function onPopupShowing(sender, args) {
var checkBoxChecked = $get("<%= chkDDMandate.ClientID %>").checked;
args.set_cancel(!checkBoxChecked);
}
</script>
After Yuriy provided me with the event handler, I had to resort to using hidden fields to keep track of the visibility of the popup and the checkbox.
This was because I didn't want the popup to appear when the tick was being removed and the fact that the onClick method used the setting the checkbox control was being set to, whereas the onShowing method was using the current visible setting of the control. I had to use the hidden fields to keep the visibilty settings and update them at the time I wanted.
I'm surprised that the _visible property of the popup extender was always set to 'false', so I couldn't use that either.
This may be a bit of a hack, but this is my current javascript code for anyone that is interested:
<script type="text/javascript">
function pageLoad() {
// Attach an event handler for over-riding the showing Popup.
var extender = $find("PopupControlExtenderBehaviorID");
extender.remove_showing(onPopupShowing);
extender.add_showing(onPopupShowing);
// Initialise the hidden fields based on the page status after refresh.
var hfPopup = $get("ctl00_body_PopupVisibleID");
var hfCheckbox = $get("ctl00_body_CheckboxChecked");
// Popup will always be hidden on page refresh
hfPopup.value = "Hidden";
hfCheckbox.value = $get("ctl00_body_chkDDMandate").checked;
}
function onPopupShowing(sender, args) {
// This function will over-ride the Popup showing if applicable.
var popupVisible = $get("ctl00_body_PopupVisibleID");
var checkboxChecked = $get("ctl00_body_CheckboxChecked");
// If Popup hidden and 'tick' being taken out of the Checkbox, don't show the Popup.
if (popupVisible.value == "Hidden" && checkboxChecked.value == "true") {
args.set_cancel(true);
}
else if (popupVisible.value == "Hidden") {
popupVisible.value = "Visible";
}
else {popupVisible.value = "Hidden";}
}
function OnClientClickCheck(o) {
// This function will set the Hidden field value of Checkbox.
// This is because when the OnClick method reads the control checkbox value it uses the value it's
// being set to; whereas, the onPopupShowing method uses the value it is currently displaying!
var pce = $find('PopupControlExtenderBehaviorID');
var checkboxChecked = $get("ctl00_body_CheckboxChecked");
var isChecked = o.checked;
if (isChecked) {
// isChecked is what it is being changed to...
checkboxChecked.value = "false";
}
else {
checkboxChecked.value = "true";
}
pce.showPopup();
}
</script>
Thanks for the help in getting here.