I'm trying to fix a bug I've encountered with a button not triggering in my webform.
The code for the button in the aspx file and the vb file looks like this:
<asp:Button ID="btnUserEditSave" runat="server" Text="Save User" ClientIDMode="Static" CssClass="button saveButton xbtnWaitEvent" width="100px" ToolTip="Save changes" />
Protected Sub btnUserEditSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUserEditSave.Click
I haven't included to code for the button itself as it's irrelevant because the bug relates to the button not triggering rather than the code of the button itself breaking. I've tested how the button works and what causes it to not trigger and here's the information I have thus far:
When first saving user details through this button, the button triggers and all code runs as expected. The page is the reloaded with the new user details showing.
However after doing this, the button will not trigger properly and when clicked will cause the page to go blank. This is despite the fact that no page load methods written in the source trigger either nor does the Javascript seem to either which I've tried testing through the use of alerts (see code below):
if(document.getElementById('btnUserEditSave').clicked == true)
{
alert("button was clicked");
}
It is worth noting that the other buttons on the page also do not work again in a very similar way. The code behind the button does not trigger nor does a page load method trigger. But a blank page is still shown.
If any further code is needed for context then I will provide as much as I can, and any help as to what might be causing this error would be greatly appreciated as I am rather stuck for ideas. Thanks.
You need to add the onclick event in the html markup, that's how you wire it up.
<asp:Button ID="btnUserEditSave" onclick="btnUserEditSave_Click" runat="server" Text="Save User" ClientIDMode="Static" CssClass="button saveButton xbtnWaitEvent" width="100px" ToolTip="Save changes" />
I am attempting to submit form data from within a javascript popup window.
The popup opens fine and displays all elements as expected. When I click the asp:button, before inputting anything, it performs required field validation as expected. All of that is working just fine.
The problem I am having is in getting the OnClick to work and submit the form data.
To say I am a beginner to javascript/JQuery is an understatement, so requesting a bit of hand-holding on this one. Thanks in advance for the help.
<asp:Button ID="submitRes" CssClass="button" runat="server" ClientIDMode="Static" Text="Submit This Form Data" OnClick="Submit_Click" />
$( document ).ready(function() {
$(document).on("click", ".divPopupAdd", function(event){
showPopup()
});
function showPopup(){
$("#popup_add").dialog({
show: { effect: "blind", duration: 200 },
resizable: false,
modal: true,
width: 750,
height: 450,
open: function(){
$('#<%=submitRes.ClientID %>').click();
}
});
}
});
Ok, this is how you post back - click a button to run your code behind.
We going to lay this out step by step.
We assume, that you click a button on your form, and it launches the jQuery dialog? Beyond important here that this “is” in fact your flow in this form.
So, I’m going to assume user clicks a button, and the dialog is launched.
(and avoid that document on-ready. Please dump it).
Now the dialog is displayed. In that dialog, we assume user enters data, does whatever, and THEN either clicks a button for ok, or clicks a button to cancel?
Next up:
You CAN NOT do/use an asp.net button for a post back in that dialog. It WILL NOT work – end of story!
And if you did get the post back to work, it would mess up your current page “dom” that is holding the current web page, and also that of the dialog. It just does not work – don’t do it, ok?
(so no post backs in that dialog!!)
But we can still happy make this work!!!
So, how do we setup a button in the dialog?
Lets assume you need to click a button inside the dialog?
Button MUST be client side JavaScript (js).
That button will:
Close the dialog, and THEN do the post back.
So, we thus need this flow:
Display dialog on button click (client side js).
User does whatever in that dialog.
User now clicks on a button (say ok, or cancel).
We CAN and will for the sake of going crazy? We will drop on the form and use standard asp.net buttons. There is really no need to adopt HTML “input” buttons. (You can, but no real need here).
I am going to use BOTH built in jQuery buttons and ALSO two standard buttons in that dialog (the reason is many, but that way YOU can choose either way, and learn this. (boy, do I with someone had laid out how this works for me!!!). So, I going to save you much pain and suffering here.
So, lets start from the top:
Our button code to pop the dialog.
The asp button will be this:
<asp:Button ID="showdialog" runat="server" Text="Show the dialog"
OnClientClick="showpop();return false;"/>
Note close in above!!!!
We use OnClientClick=showpop();return false.
This will thus run js code, and NOT do a post back. The return = false is VERY important here, since if you leave that out, then the standard asp button will post back like it “normally” does. And we break our new rule!! – no post backs inside the dialog!!.
Ok, so that is the button to launch the dialog.
The js code to launch the popup is similar to what you have.
Eg this:
function showpop() {
var mydiv = $('#popdialog');
mydiv.dialog({
autoOpen: false, modal: true, title: 'My cool dialog, width: '30%'
});
// Open the dialog
mydiv.dialog('open');
}
Now, again for this example, we assume that you dropped some standard asp buttons in that dialog. But, OFTEN you want to use the built in dialog buttons. So let’s do BOTH for this example.
So, the above code thus becomes this:
function showpop() {
var mydiv = $('#popdialog');
mydiv.dialog({
autoOpen: false, modal: true, title: 'My cool other page', width: '30%',
position: { my: 'top', at: 'top+150' },
buttons: {
'ok': mycustomok,
'cancel': mycustomcancel
}
});
// Open the dialog
mydiv.dialog('open');
}
Note the two built in buttons we added. (ok, and cancel).
Note how I also broke out the 'setup' and THEN the one line that pops the dialog.
And in our pop up div, we also have two custom buttons. As noted, I am including both custom and built in dialogs. This will take you “hours” to get nice examples of this, and now you can choose either road.
So, our div has some text, and two custom buttons, and a simple text box.
The div looks like this:
<div id="popdialog" runat="server" style="display:none">
<h2>My cool pop dialog</h2>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="MyOk" runat="server" Text="My custom ok"
OnClientClick="mycustomok();return false;"/>
<br />
<asp:Button ID="MyCancel" runat="server" Text="My custom cancel"
OnClientClick="mycustomcancel();return false;"/>
</div>
The only real thing to note in above is the style=”display:none” for the WHOLE “div”. This will thus hide the div, and it will not display when the page loads.
So, when we click on the button, it will show the dialog. You will see this:
So, we have our two custom buttons, and the two jQuery but in buttons. If you don't want the built in ones then use my first sample code. As I stated, your choice as to which buttons you want, like, or feel to use here. The main point is that BOTH sets of buttons do the SAME thing.
So, for this example, you click “ok”, or “my custom ok”.
Either way? We want our post back to run for that choice.
And for my custom cancel, or the built in cancel, we want code behind (server code) to run for that cancel choice. Do keep in mind you often don't need any code - but JUST the dialog to close and cancel and do nothing.
So, the two js stubs we have for this are:
function mycustomok() {
// first, close the dialog
$('#popdialog').dialog('close');
#('#HiddenOk').click();
}
function mycustomcancel() {
// first, close the dialog
$('#popdialog').dialog('close');
$('#HiddenCancel').click();
}
As noted, if you use BUILT IN buttons for the dialog, then you do NOT need the “close” of the dialog I have above. But your using (we assume) custom buttons, and not the built in jQuery ones.
And as noted, based on either choice, we will do a post back and run code behind. As I stated, the short way, easy way is to drop two hidden buttons on the form, they will look like this, and of course our outside the above div
<asp:Button ID="HiddenOk" runat="server" Text="hidden ok"
style="display:normal"/>
<asp:Button ID="HiddenCancel" runat="server" Text="hidden cancel"
style="display:normal"/>
Note careful (note BEYOND carefull here).
I have display = normal for the two buttons. The reason is that then with the designer you can double click on the button, and write your code behind. When you are DONE and have both code behind stubs written, then change the above display:normal to display:none to hide them. So we left the buttons visible for easy development. Once you wired up the code behind (simply double click on the buttons in the designer), then you are jumped to the code behind editor, and can write that code.
I have this for now:
Protected Sub HiddenOk_Click(sender As Object, e As EventArgs) Handles HiddenOk.Click
Debug.Print("dialog ok code run")
End Sub
Protected Sub HiddenCancel_Click(sender As Object, e As EventArgs) Handles HiddenCancel.Click
Debug.Print("dialgo cancel code")
End Sub
Of course you write whatever you need. As noted, you may well not need any code for the cancel button – you can leave that out of this design if you wish.
So, with the two code subs automatic wired up for you (this is why we all love asp.net forms, right???).
The “click” button trick as noted is rather nice. It solves a LONG list of issues, and does so with great ease.
You get the needed post back.
You get to run your own cute little code stub behind.
You don't have to write up ajax calls to do this!!!
So this follows the whole asp.net design pattern in which you drop buttons on a form, click them, and you get to run that nice little short code behind stub. And it all wired up automatic for you.
Thus in summary:
Don’t try + attempt post backs in the dialog – you REALLY can’t do this.
And you find they don’t work anyway! So buttons on that dialog WILL run “js” code.
you can use asp buttons if you want, just remember the extra return=false part.
If you must set/send some information to the server in that dialog before you close? Well, that is a different question and answer. But the jQuery "ajax" method works REALLY nice, and you can directly call functions in your existing web page code behind, and do so with next to no effort. You don't even have to know how to setup web methods - asp.net will do all the dirty work. but lets leave that example for another day.
Try the above idea - the "click" button trick in js really is the magic key to making this all oh so very easy to write and setup.
If you wish to call the JavaScript popup from Backend side you can use ClientScript.RegisterStartupScript
Syntax:
ClientScript.RegisterStartupScript(Type type, string key, string script, bool addScriptTags)
Parameters
Type: The type of the startup script to register. This is of type 'Type'
key: The key of the startup script to register. This is of type String
script: The startup script literal to register. This is of type String
addScriptTags: A Boolean value indicating whether to add script tags. This is of type bool - true or false.
You can write like this:
protected void Button_clilck(Object sender, EventArgs e){
ClientScript.RegisterStartupScript(GetType(), "Key","showPopUp(),true);
}
And if you want to call your pop up method from Front End side you can simply call the JS method in asp:button by writing OnClientClick
<asp:Button ID="submitRes" CssClass="button" runat="server" ClientIDMode="Static" Text="Submit This Form Data" OnClick="Submit_Click" OnClientClick="showPopup" />
I have a basic JS flashcard game I made. There are 12 "answer buttons" for a user to choose from.
On mobile, the answer buttons retain the hover effect/focus(?) after being tapped (this does not happen on desktop, any browser). This is very confusing from a user standpoint as it can appear as though the app/flashcard is stuck or not updating.
I'm using Bootstrap 4.1.
Here is my button code, but there's nothing unusual about it:
<button type="button" id="E" class="btn btn-lg btn-info ansBtn" value="E">Answer</button>
I've looked at similar questions (but they were regarding bootstrap 3), which suggested using either an anchor tag instead of the button tag, but that didn't work (with and without the href attr).
I've also tried another suggestion to include this bit of jQuery, but it doesn't seem to work with 4.1 either. I've used button ID, and other classnames, but it has not worked.
$(".btn").mouseup(function(){
$(this).blur();
});
Suggestions? Thanks!
Update
So here is the latest. I've added the below CSS. This give mobile users the experience I want (a "flash" of background-color/border-color change only on click/tap). HOWEVER, now when using my macbook pro and TAPPING with my trackpad, the effect does not occur! It works when I click with the trackpad, but not tap with the track pad. :(
.btn.btn-info {
background-color: #17a2b8
}
.btn-info:not(:disabled):not(.disabled).active,
.btn-info:not(:disabled):not(.disabled):active,
.show > .btn-info.dropdown-toggle {
background-color: #117a8b;
border-color: #10707f;
}
You can always add a .setTimeout() function on the objects .onHover() or .onClick() event. This will allow your flashcard to be flipped/blurred after a certain amount of time. Alternatively, you can simply change the functionality of your application for mobile browsers and make it so you have to click to see the answer. You should also look into the .focus() method and possibly try to change focus to another element on the page. If none of this is working, it is probably some quirk with jQuery. I would suggest trying to selct the element this way:
document.querySelector(".btn").onmouseup = function(){
this.blur();
});
or:
document.querySelector(".btn").onmouseup = function(){
document.body.focus();
});
I have identified a problem with __doPostBack and found a work around. I am seeking an explanation for the cause and/or a better solution than my work around.
Scenario:
I have a dropdown populated with the values; "-Select-", "One" & "Two". If the user selects "One" than client side script is executed. If the user selects "Two" than server side script is executed.
Problem:
The client script initiates the postback by calling __doPostBack. However, no post back actually occurs unless there is also a LinkButton, Calendar or WizardStep control on the page. I actually went through all of the standard tools in the Visual Studio Toolbox and tested them all. It has to be one of those three.
Work Around:
Add a link button surrounded by a span with display set to none.
<span style="display:none;">
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</span>
Question: Can somebody provide an explanation for this behavior or provide a better fix than my "Work Around"?
Source - Javascript (I placed it between the head tags)
<script language="javascript" type="text/javascript">
function DropDownList1_change(elementRef) {
var selectedIndex = elementRef.selectedIndex;
if (selectedIndex > 0) {
var selectedValue = elementRef.options[selectedIndex].value;
if (selectedValue == "One") {
alert("Because you selected 'One', special javascript code will be executed");
// Special javascript code goes here
return;
}
else if (selectedValue == "Two") {
// Special server code gets executed on server DropDownList1_SelectedIndexChanged
__doPostBack('DropDownList1', '');
}
}
}
</script>
Source - ASPX Controls
<asp:DropDownList ID="DropDownList1" runat="server" onchange="DropDownList1_change(this)" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>-Select-</asp:ListItem>
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
</asp:DropDownList>
<br />
<!-- For some unknown reason __doPostBack only works if there is a LinkButton, Calendar or WizardStep control on the page -->
<span style="display:none;">
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</span>
Time of last Post Back: <asp:Label ID="Label1" runat="server"></asp:Label><br />
Time of OnSelectedIndexChanged: <asp:Label ID="Label2" runat="server"></asp:Label>
Source - Code Behind
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DateTime.Now.ToLongTimeString();
}
Additional Resource - I found the following article after posting this question. Its a very old Microsoft article and the only Microsoft article I found that mentions the specific limitation of DropDowns, return values & postbacks. I haven't digged deep into their solution and not sure time will allow me to. Mainly posting it in case my solution fails down the road or doesn't work for someone else.
Intuitively you might think adding a confirm dialog box for a
DropDownList is identical to adding such a dialog box for a Button Web
control. That is, simply set the DropDownList's client-side onchange
attribute to something like: return confirm(...);. using:
DropDownListID.Attributes("onchange") = "return confirm(...);"
Unfortunately, this won't work as desired because an AutoPostBack
DropDownList's onchange attribute will be set to a bit of JavaScript
that causes a postback, namely a call to the client-side __doPostBack
function. When setting the onchange attribute programmatically
yourself, the end result is that the rendered client-side onchange
event handler has both your code and the call to __doPostBack:
The article is long so search for "Confirmation with AutoPostBack DropDownLists"
https://msdn.microsoft.com/en-us/library/aa479302.aspx
There are 2 solutions.
Solution 1:
A better work around than adding a link button surrounded by hidden span tags is to add the following to the page load event. This ensures that the function __doPostBack is available.
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.GetPostBackEventReference(this, string.Empty);
}
The function __doPostBack is generated only if a control in the form needs it to perform postbacks. This includes controls like the LinkButton and other controls for which AutoPostBack is set to true. In fact, only the Button and ImageButton controls can perform postbacks without __doPostBack (see this article). For example, we can see in the HTML output that a LinkButton is rendered this way:
<a id="lnk" href="javascript:__doPostBack('lnk','')">My link</a>
Solution 2: The following approach achieves the same thing without using __doPostBack.
In the present case, you could set AutoPostBack="true" for the DropDownList:
<asp:DropDownList AutoPostBack="true" onchange="if (!confirmPostBack(this)) return false;" ... >
The onchange event handler would return false when you want to prevent the postback. The Javascript function could be something like this:
function confirmPostBack(ddl)
{
if (condition) {
...
return true;
}
else {
...
return false;
}
}
Important: The onchange event handler should not return anything to allow the postback to occur. You can use this syntax:
onchange="if (!confirmPostBack(this)) return false;"
For reasons probably explained in the article mentioned in the question, the following syntax does not work. Returning true still prevents the postback.
onchange="return confirmPostBack(this);" // Does not work!
I have to integrate a Java applet into a simple asp.net 2.0 control.
This applet is a bought product and cannot be modified. It contains a button designed to be clicked to continue. The button click is linked to a JavaScript function.
So we can see this applet as a black box, eating data and calling a JS function when it's done.
I have to make a postback when the JS function is called to go to the next page. Easy, I just have to write it. But I would also like to hide the applet, or the div containing it, because the postback trigger some long treatment. The point is that, while waiting, the user can click on the applet button and triggers the postback again.
In my JavaScript called function, I tried many solutions:
Make 2 postbacks. Of course this doesn't work, as a postback is a reload of the page
Hide/show the div or the applet using JavaScript
Hide/show the div or the applet using jQuery
Hide/show the div or the applet calling the click event of an invisible button to set Visible = false in the code behind
But it always fails: it seems that the web browser (IE 8.0 or Chrome) waits the end of the postback/JS function to update the page, and don't bother with some UI update just before.
So here I am:
I need the postback to go to the next page (I do not control the entire environment where my control is used)
I have to hide the applet, otherwise the user can re-click on it
I can't make a two-step process, like having the JS function hiding the applet and displaying a link to to the next page, involving a new click
My simple control:
<%# Control Language="C#" AutoEventWireup="false" Codebehind="MyControl.ascx.cs"
Inherits="MyControl" %>
<div id="m_DivPostDisplay" runat="server">
<asp:Label ID="lblState" runat="server" Text="Displaying something like please wait..." />
</div>
<div id="m_DivAppletContainer" runat="server">
<applet name="myApplet" archive="./myJar.jar"
code="Main.class" height="700" width="530" mayscript>
</applet>
</div>
The related javascript (injected when the page load):
<script language='javascript'>
function sendData(data) {
// This is where I try to hide the applet or the div
//.....
// Go to the next page
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(\"nextButtonId\", \"\", true, \"\", \"\", false, true));
}
</script>
Do you have any idea of what could be done to fix my problem?
Thanks :)
Ugly, but you could try :
function sendData(data) {
// hide applet
setTimeout(function () {WebForm_DoPostBackWithOptions(...);}, 500);
}
Finally we asked the applet editor to add a new feature, so we can now disable its buttons when we need.
So when we click on the button, we keep it disabled, launch the postback, and change page when the postback returns.