Why textbox loses masking upon postback ? - c#

I have asked this question many time at different intervals at different forums but nothing helped me out but in hope I am posting it again. Please help.
I have applied JqueryMasking to a textbox i.e. NIC masking. It works when Page loads initially but stop working when postback occurs i.e. no mask is applied then. Why ?
jQuery(function ($) {
$("#txtBoxComplainantCNIC").mask("99999-9999999-9", { placeholder: "" });
});
textbox:
<asp:TextBox ID="txtBoxComplainantCNIC" runat="server" onkeypress="return isNumberKeyCNIC(this)" ClientIDMode="Static" placeholder="XXXXX-XXXXXXX-X" MaxLength="15" CssClass="form-control"></asp:TextBox>
Textbox resides in UpdatePanel.

It looks like your problem is that you have registered a function with JQuery to execute when the page loads. That is what
jQuery(function ($) {
$("#txtBoxComplainantCNIC").mask("99999-9999999-9", { placeholder: "" });
});
does. However that means that code will only execute when the page loads. Your problem is that in an UpdatePanel, your postback happens asynchronously (no page load), so your function doesn't fire a 2nd time and your TextBox loses it's mask.
What you probably want to do is register this part of your script
$("#txtBoxComplainantCNIC").mask("99999-9999999-9", { placeholder: "" });
in code behind so that ASP.NET knows to execute it when your UpdatePanel posts back. It will look something like this:
void Page_Load(object sender, EventArgs e)
{
var setMaskScript = "$('#txtBoxComplainantCNIC').mask('99999-9999999-9', { placeholder: '' });";
ScriptManager.RegisterStartupScript(updatePanelID, this.GetType(), "SetMask", setMaskScript, true);
}
where updatePanelID is the ID of your UpdatePanel.
Here is a link that explains RegisterStartupScript and it's interaction with UpdatePanel.
Additionally, several methods for executing code on UpdatePanel postback are discussed here. One of which is simply adding a pageLoad function to your client side code.
pageLoad(){
$("#txtBoxComplainantCNIC").mask("99999-9999999-9", { placeholder: "" });
}

On the control that is posting back the page use the below code:
ScriptManager.RegisterStartupScript(Page, Page.GetType, "temp", "<script type='text/javascript'>$('#txtBoxComplainantCNIC').mask('99999-9999999-9');</script>", False)

Related

OnClientClick custom message box before Onclick event handler not working

I wanted to have a Custom Message Box OnClientClick . If the User Selects Yes then the Onclick Event handler in the C# code should get trigger. But somehow i am not able to do this using ASP.net and jquery.
As of now what is happening
Only C# code is triggered
What i was expecting
ClientSide Confirmation message (If User Clicks "YES" ) Then Server-side
code triggers.
My HTML
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSubmit" Text="submit" runat="server" OnClick="btnDelete_Click"
OnClientClick="if(!ShowDeleteFormConfirmation()) {return false;};" />
</div>
</form>
Jquery
function ShowDeleteFormConfirmation() {
var confirmationMessage,
dlgButtons = {
"No": function () {
$(this).dialog("close");
return false;
},
"Yes": function () {
$(this).dialog("close");
return true;
}
};
confirmationMessage = "This form has already been assigned and will be marked as deleted.";
var $panelContainer = $("<div>" + confirmationMessage + "</div>").appendTo('body');
$panelContainer.attr("title", "Confirmation to delete a form");
var myPos = [$(window).width() / 2 - 100, 50];
$panelContainer.dialog({
modal: false,
draggable: false,
position: myPos,
button: dlgButtons
});
}
C# ////OnClick
protected void btnDelete_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Delete button clicked.');", true);
} ```
This is what i wanted to implement.
http://jsfiddle.net/y5z01nbr/
Thanks for having a look.
Ok, while your code would work if you used "confirm" in the js code, that's because alert() and confirm() HALTS the calling code.
However, today, near ALL WEB code libraries are written to NOT halt, and NOT freeze up the browser. And jQuery is one such system. (it does not HALT the code). While I could introduce the concepts of await - that's becoming a wee bit too complex for this POST.
So, what this means:
the jQuery code does NOT halt,
and thus when you click on the button,
the client side code runs WITHOUT halting
and thus the button click (server side code) will
ALSO run right away - not waiting.
So, in the case of a jQuery dialog? You can't HALT the code. this means you have to flip this backwards. The jQuery dialog is to be displayed, AND THEN you have to call/run/click on that server side button. So, you have to add a new button, and use style="display:none" ot the existing button. Then display the dialog, and based on the answer you THEN click on (call) that origional button you have/had now.
The code will thus look like this:
<div>
<asp:Button ID="btnSubmit" Text="submit" runat="server" OnClick="btnDelete_Click"
Style="display:none" clientIDmode="static" />
<asp:Button ID="btnSubmitX" Text="submit" runat="server"
clientIDmode="static" OnClientClick="ShowDeleteFormConfirmation();" />
<\div>
So I dropped in another button - no server behind code. Hide first button with display none, and removed the client click. I moved the client click to 2nd button.
Now, we can do this:
dlgButtons = {
"No": function () {
$(this).dialog("close");
},
"Yes": function () {
$(this).dialog("close");
$('#btnSubmit').click();
}
};
So what we do is launch the dialog. And based on yes, then we click our button. If you choose no, then the dialog is dismissed, but no other action need take place.
A a GENERAL hard and fast rule?
Your browser code is RARE these days blocking code - calling a jQuery.ui dialog and in fact most of these newer UI controls? The code does NOT wait, does NOT halt. And this means you can't use the return true/false to control if the server side event stub will run or not (you can use js confirm(), but not jQuery, since it don't wait, nor halt the code).

Input "Reset" button fails to work when a grid is shown in page

I have an Advanced Find Form that contains a few asp:textbox controls as well as asp:dropdownlist controls. When I hit my reset button, it works well in clearing or resetting my textboxes and dropdownlists.
However, when the user clicks "Go" to submit the search query and a grid is shown with the results, the reset button no longer works.
Here's my input button:
<input type="reset" value="Clear All" />
EDIT:
Please note that I need to reset the fields to "Default Values" and also I need to be doing without a postback, to be doing it on client side
Have you try with normal button :
<asp:Button ID="txtResetbtn" runat="server" OnClick="txtResetbtn_Click" />
protected void txtResetbtn_Click(object sender, EventArgs e)
{
TextBox1.Text = string.Empty;
}
I think the problem is that HTML button don't reset after a postback
Or you can try to do this in the :
<asp:Button runat="server" ID="reBt" Text="Reset"
OnClientClick="this.form.reset();return false;"
CausesValidation="false" />
From : Reset a page in ASP.NET without postback
That link can help you too : Is there an easy way to clear an ASP.NET form?
The input type "reset" does not clear the form, it resets the form to its default values. To clear the form after submitting, you'll have to use javascript to set all values to empty.
Edit:
Since you're using asp.net, you could also use an <asp:button /> to call a method that clears the values of each control in the form.
Edit 2:
If you need to keep this function client-side, you'll have to use Javascript. Also, I think it's important to make a distiction between resetting to a default value (what the "reset" input type does) and clearing the values in a form, even after a submit. To do the later on the client side, you'll have to write a little javascript.
I managed to workaround the problem. As TenneC and Nikolay have mentioned in previous answers, I used an ASP.Net button but I've performed the reset function using jquery as follows:
$(document).ready(function(){
$("#BtnClear").click(function () {
$('#FillForm input').val(function () {
return this.defaultValue;
});
$('#DDLId1').val(function () {
return this.defaultValue;
});
$('#DDLId2').val(function () {
return this.defaultValue;
});
});
});

ASP.NET Button OnClientClick

I have question and any help will be greatly appreciated. I hope I am explaining this clearly, but if i'm not just let me know, i will be on for a while. This is written in C# and I have a button that calls a javascript function called "JavaScript()" in the "OnClientClick" part and in the "OnClick" part I have an "if statement" where the first part resembles the OnClientClick function and the second part represents different code that is not related to the OnClientClick.
DefaultPage.aspx:
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_OnClick"
OnClientClick="JavaScript()" />
DefaultPage.aspx.cs:
protected void Button1_OnClick(object sender, EventArgs e)
{
String a = getValueofA();
If (a == "1")
{
//OnClientClick code goes here
}
else If (a == "2")
{
//No OnClientClick code goes here
}
}
This javascript function comes from a different Web Control that I am loading on this "DefaultPage". This worked perfect for me until I added the "if statement" in Button1_OnClick. Originally I just had the first part of the "if statement", now I need to add the second part of it. How can I accomplish this. I tried button1.OnClientClick, but it only works in Page_Load. I need to first determine the value of "a" then proceed. Sorry if i'm not clear but i can answer any questions. Thanks so much. My goal is to remove the "OnClientClick=JavaScript" from my asp.net button and just call that function inside the if statement.
What error are you getting? If is not capitalized in C#.
http://msdn.microsoft.com/en-us/library/5011f09h(v=vs.100).aspx
EDIT:
Based on the comments, I think you are better off going client side entirely.
<script type="text/javascript">
function NewFunction(){
var a = getValueOfA();
if (a === "1")
{
JavaScript();
}
else if ( a==="2" )
{
//other code
}
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="NewFunction()" />
I am not sure if I understood your questions, it seems like you want to execute javascript code from the code behind. How about using ScriptManager in the code behind and execute javascript from there? like below
// write your onclientclick code here
ScriptManager.RegisterStartupScript(this, typeof(string), "JAVA_SCRIPT", "your javascript() function code here", true);

Need assistance with jQuery and ASP.NET want to show/hide a panel on click of a button, but the postbacks mess it up

RESOLVED
how do i set question to resolved? lol
Anyways here is the sollution, I had my friend help me and he did it!
First since as I said I was using an update panel the jQuery didn't register the partial postbacks from it and that was the main problem. A slightly lesser problem why it didn't work without an update panel was the 1 and 0 values in the function on click being swapped mistakenly.
So first we did an override on the OnInit method, but you can put the same code in pageload too(except the call to base on init code ofc) :) :
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
prikazi.Attributes.Add("onclick", "return LinkKlik();");
ScriptManager.RegisterStartupScript(this, this.GetType(), "init", "checkComponent();", true);
}
Where we register a script to run every time the page gets reinitialized, even with async postbacks :) and we add the click function to the linkbutton here as well.
the jquery code is as follows:
function checkComponent() {
//
if (document.getElementById('hidTracker').value == '1') {
$(".sokrij").show();
}
else {
$(".sokrij").hide();
}
}
function LinkKlik() {
var panel = $("#fioka").find(".sokrij");
if (panel.is(":visible")) {
panel.slideUp("500");
$('#hidTracker').attr("value", "0");
}
else {
panel.slideDown("500");
$('#hidTracker').attr("value", "1");
}
// that's it folks! (return false to stop the browser jumping the the '#' link
return false;
}
It's basically the same as before, just divided in 2 functions linked to events by the override above.
one last thing, you need these:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript" src="drawer.js"></script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<asp:HiddenField ID="hidTracker" runat="server" Value="0" />
<div id="fioka">
<asp:LinkButton runat="server" href="#" ID="prikazi">Click This to show/close</asp:LinkButton>
<div class="sokrij" id="sokrij">
HIDE THIS!!!
</div>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="prikazi" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
It even works inside the update panel. the button is there to generate postbacks, and you can even put one outside to generate real postbacks outside the update panel. The value of the state is recorded in the hidden field, and the linkbutton is the one we use to show/hide. Cheers if anyone ever needs this, cause i saw lots of posts about the same thing but none of them answered it.
Thanks guys for answering, especially CRAB BUCKET
I would give u all +rep if i could but as u can see just starting.
I have a control in which i have various elements that do postback. I
have that control in my main page in an update panel, and it works
great. What i want to do is hide half of the elements and to be able
to show them only when button is clicked. I managed to find some
jQuery drawers and it looked fine, but whenever I opened the panel and
changed an element which had a postback to call a c# function on click
or value change the drawer is opened (no matter if i press the open
drawer link).
my elements have to have postbacks! and i need that drawer show/hide
thingie to hide half of them...
here's what I have on the drawer so far, by putting together some code
myself. As I said with this code it i click any button that causes
post back, the drawer is opened after the postback even if i didn't
click the open drawer link. Other than that it works ok between
postbacks, but I have to have it working even with postbacks!
$(function () {
$(".sokrij").hide(),
$("#prikazi").live("click", function (evt) {
evt.preventDefault();
$("#fioka").find(".sokrij").each(function () {
if ($(this).is(":visible")) {
$(this).slideUp("500");
}
});
if ($(this).next().is(":hidden")) {
$(this).next().slideDown("500");
}
return false;
});
});
I need a way to make the postbacks not influence the state of the
drawer. If it is open I want it to stay open after a postback, and if
it is closed to stay closed after postback. So that means I need it to
remember it's state and check it after every postback!
Here is my tag structure.
<div id="fioka">
Click This to show/close
<div class="sokrij">
</div>
</div>
MAJOR EDIT:
Here is what I have now, after the input from Crab Bucket:
tag structure:
<input type="hidden" ID="hidTracker" value="0" />
<div id="fioka">
Click This to show/close
<div class="sokrij">
</div>
</div>
and that's all inside an update panel in which there are buttons that
generate postbacks, but those postbacks do not refresh the main page,
they are contained inside the update panel.
and the jQuery code is thus far:
$(document).ready(function () {
if ($('#hidTracker').val() == '1') {
$(".sokrij").show();
}
else {
$(".sokrij").hide();
}
$("#prikazi").live("click", function (evt) {
evt.preventDefault();
var panel = $("#fioka").find(".sokrij");
if (panel.is(":visible")) {
panel.slideUp("500");
$('#hidTracker').val('1');
}
else {
panel.slideDown("500");
$('#hidTracker').val('0');
}
return false;
});
});
So it now works like this: On the site load, it shows the panel
(drawer) closed. If i click the link to show/hide panel it works
superb. But after one of the buttons generates a postback it refreshes
the panel and it shows up OPEN every time a postback is generated.
After the postback I can still use the open/close link to open/close
it and that works well, but i need a way to save the sate the panel
was before the postback and set it in that state after the postback.
The code crab bucket provided with the hidden field should work for that too, but it doesnt, and i think i need some way to execute the
check for whether the panel was open or closed after a postback. as it
is the check only happens on the page load, but not after
postbacks!!!
You need to do the state tracking yourself. I've used my own hidden field for this i.e.
<input type="hidden" ID="hidTracker" value="0" />
and at the top of your function
if($('#hidTracker').val() == '1')
{
$(".sokrij").show();
}
else
{
$(".sokrij").hide();
}
then change your main function body to track state manually
$("#fioka").find(".sokrij").each(function ()
{
if ($(this).is(":visible"))
{
$(this).slideUp("500");
$('#hidTracker').val('0');
}
});
if ($(this).next().is(":hidden"))
{
$(this).next().slideDown("500");
$('#hidTracker').val('1');
}
BUT
This is only going to work for one panel - which isn't your case. So you are going to have to finnese this process to link the state to the id of the panel being shown hidden.
I've done this before by using the same principle but recording a JSON string in the hidden field then rehydrating it gives the ability to add structure key/value information to record the state
The JSON in your hidden field might look like this for two panels
{"panelState": [{ID:"pnl1", "State":"1"}, {ID:"pnl2", "State":"0"}]}
and here is a json parser to help you construct and rehydrate the strings.
It's going to a a bit of work to get it going but this is the start. If i get time I will flesh it out a bit more but i can't promise - sorry
EDIT
To adapt for one panel try
var panel = $("#fioka").find(".sokrij");
if (panel.is(":visible"))
{
panel.slideUp("500");
$('#hidTracker').val('1');
}
else
{
panel.slideDown("500");
$('#hidTracker').val('0');
}
Don't forget to wrap all your code in
$(document).ready(function(){
//all my code
});
Otherwise the DOM isn't guaranteed to be loaded and the code may not execute correctly
EDIT 2
It's hard to get the show hide code trackering javaScript but this strange function hooks into the update panel and will fire when the update panel posts back. This will allow your update panel to track the panel state
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) {
if($('#hidTracker').val() == '1')
{
$(".sokrij").show();
}
else
{
$(".sokrij").hide();
}
});
Hope it helps
So if you want something to be hidden:
.sokrij
{
display:none;
}
then when you want it to be shown:
$(".sokrij").css("display","";
Edit: I misunderstood your needs. If you need to save the info use a session variable or something similar.
if(Session["state"] != null)
string state = Session["state"].ToString();
if(state == "0")
{
$(".sokrij").hide();
}
if (state == "1") { $(".sokrij").hide(); Session["state"]="0"; } }
Of course you can change the strings to integers or boolean or whatever.

Executing JavaScript function in Code behind -- How to Get the Return Value in Code Behind

I have following JavaScript function, Which call Jquery JSON function and get the DateTime with respect to timezone. This works fine.
<script type="text/javascript">
function JSFunctionName() {
$(document).ready(function () {
var timezone = "US/Central";
$.getJSON("http://json-time.appspot.com/time.json?tz=" + timezone + "&callback=?",
function (data) {
if (data.hour < 12) {
//alert(data.hour + ':' + data.minute); // want to return this value data.hour + data.minute
//document.getElementById('<%=HiddenField1.ClientID %>').value = data.hour + ':' + data.minute;// this does not work
}
})
});
}
</script>
Now I am calling this Javascription function in Code behind on onclick of button
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Code behind
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"alert", "JSFunctionName();", true);
// here I need the DateTime value that is get from JSON
//Response.Write(HiddenField1.Value);
}
How can I return the value from Javascript to code behind immediate after call of Page.ClientScript.RegisterStartupScript
Please note I have try to set the value in HiddenField, but its not working. you can see in the comment.
Any idea or alternative solution will be appreciated.
Thanks
You can't do this without posting back to the server. The reason for this is that javascript executes on the client, and it will only execute after the page has left the server.
I assume this is a contrived example, but in this specific case, if you want to have the same information available on the client and server, you need to compute it on the server, and pass that out to the client.
If this isn't possible, you'll need to create a webservice, but that will have to handle the response asynchronously.
You can use ajax call to server from the javascript function or you may put another button on the form, hide it with style and cause click on this button after you set up calculated value to the hidden field in the JSFunctionName function.
Your problem is that the following line:
Page.ClientScript.RegisterStartupScript(this.GetType(),
"alert", "JSFunctionName();", true);
doesn't actually "execute" the Javascript funciton. It just adds the
JSFunctionName();
to the page in a script block, to be executed after your code has completed, and the page has loaded.
Rather than "calling the Javascript" from your button-click event, you could set the "OnClientClick" property of the button to "JSFunctionName()":
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" OnClientClick="JSFunctionName();" />
This will cause the JSFunctionName to fire before the postback happens. You can then set up your JSFunctionName() method to return true when it's done, which will then fire the postback.
You will then be able to access the value of HiddenField1 from the server-side click handler.

Categories

Resources