I have a complicated page but I created a simple ASP.NET page with the issue. I have telerik RadAsyncUpload control and a button inside an UpdatePanel as shown:
<asp:UpdatePanel ID="_updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
<telerik:RadAsyncUpload ID="fileUpload" runat="server" MaxFileInputsCount="1" OnClientFilesSelected="fileUpload_ClientFilesSelected" /><br />
<asp:Button ID="_saveNewFileButton" runat="server" OnClick="_saveNewFileButton_Click"
Text="Save"/>
</ContentTemplate>
</asp:UpdatePanel>
When a file is selected I want to disable the _saveNewFileButton and change the text to "Please Wait for Attachment Upload..." but I can't seem to get hold of the button reference in javascript:
var FilesUpdateInterval = null;
//Handles client side FilesSelected event for _newFileUploadButton.
function fileUpload_ClientFilesSelected(sender, args) {
//disable the click event for submit button during upload
var submitButton = $find('<%= _saveNewFileButton.ClientID %>');
submitButton.set_text('Please Wait for Attachment Upload...')
submitButton.set_readOnly(true);
if (FilesUpdateInterval == null) {
FilesUpdateInterval = setInterval(function () { FileCheckForUploadCompletion(); }, 500);
}
}
I am getting submitButton is null error. I tried putting this javascript code outside the updatepanel and inside ContentTemplate with same result. Obviously whatever I am doing is wrong. How do I get hold of the control that is in updatepanel in javascript?
EDIT: I find out that $find works with only telerik controls. So, I have to either use document.getElementById function or JQuery with something like Steve specified. Also, I have to use RegisterClientScriptBlock. I will test with Steve suggestion and then accept the answer.
short version - use $get() or document.getElementById(), as regular HTML elements are not IScriptControls, so $find() will not give you anything, and they don't have the rich client API you are trying to use.
For example
var submitButton = $get('<%= _saveNewFileButton.ClientID %>');
submitButton.setAttribute("value", "Please Wait for Attachment Upload...");
Option 2 - use RadButton.
Using jQuery and vb with ASP.Net, I've done something similar to this, which has worked well, even if it isn't that pretty. The [Whatever] I have was a FormView that didn't always have the control. Also, I didn't use it with a button, but I think that's the syntax for changing the button text. Either way, it might give you some ideas:
$('#<%=GetButtonClientID("_saveNewFileButton")%>').attr('value', 'Please Wait for Attachment Upload...');
And then I have a function like this:
Public Function GetButtonClientID(ByVal argFieldName As String) As String
Dim tmpID As String = "0"
Dim tmpButton As Button = [Whatever].FindControl(argFieldName)
If Not tmpButton Is Nothing Then Return tmpButton.ClientID.ToString Else Return "0"
End Function
Related
i want to do validation asking that, are sure you want to delete..?
<asp:LinkButton ID="lnkDelete" runat="server"
CommandName='<%# DataBinder.Eval(Container.DataItem, "ImageId") %>' OnCommand="Calling_Delete">Delete</asp:LinkButton>
The easiest way to do it is to use Confirm Button extender. Just drag this control next to the linkbutton and set the Confirmbutton externders TargetControlID to the Id of the Linkbutton. Everything else will be taken care of by the control.
More info- http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx
Use OnClientClick property to attach the java-script that will do the prompting. For example,
<asp:LinkButton ID="lnkDelete" runat="server"
CommandName='<%# DataBinder.Eval(Container.DataItem, "ImageId") %>'
OnClientClick="return confirm('Are sure you want to delete..?');"
OnCommand="Calling_Delete">Delete</asp:LinkButton>
This answer has one way to do it, using jQuery and a jQuery UI dialog
One advantage of using a javascript dialog such as that provided by jQuery UI is that the popup dialog is modal only for the web page on which it is displayed. You can still access other tabs within your browser while the popup is displayed.
Other solutions that use the javascript confirm function will force the user to dismiss the confirmation dialog before switching to another browser tab.
if u'd like to use custom confirmation ( like jquery dialog,bootboxjs etc.. ) then you have to generate button's "postback string" or get it somehow. asp.net gives such as postback name after rendering the page; __doPostBack('ctl00$ContentPlaceHolder1$btnDeleteSelected',''). after realizing this i wrote a js function which is generates button's postback str;
function PostBackBtnMake(id) { // id : ContentPlaceHolder1_btnDeleteSelected
var result;
var temp = id.split('_');
result = 'ctl00$' + temp[0] + '$' + temp[1];
return result;
}
then i be able to use in custom confirmation box (in this case i used bootboxjs);
function PostBackBtn(e) {
var _result = false;
bootbox.confirm("Are you sure?", function (result) {
if (result) {
__doPostBack(PostBackBtnMake(e.id), '')
}
});
return _result;
}
it's worked for me, i hope it helps you too.
This is my label I want to display if the user have left out field before clicking the button. What am I doing wrong because nothing is happening when I click the button.
<asp:Label ID="lblError" runat="server"
Text="* Please complete all mandatory fields" style="display: none;" >
</asp:Label>
This is the function I call when I click on the button:
function valSubmit(){
varName = document.form1.txtName.value;
varSurname = document.form1.txtSurname.value;
if (varName == "" || varSurname == "")
{
document.getElementById('lblError').style.display = 'inherit';
}
else
{
.................other code go here...........................
return true;
}
}
Why not use the Validation controls? These will give you client and server side validation out of the box - not that I'm lazy or anything... ;-)
Edit for comment:
The RequiredFieldValidator can be set to display a single red asterisk by the side of each control, and a validation summary control could be used BUT that would take up space.
So, it's possible that ASP.Net is renaming your control, so your JS should read:
document.getElementById('<%= lblError.ClientID %>').style.display = 'inherit';
Give that a go...
Personally, I'd still use the Validator controls ;-)
You shouldn't be using lblError as an ID in JavaScript code. Instead you should use:
'<%= lblError.ClientID %>'
Of course this is only possible if you are generating the JavaScript code in the ASP.NET file.
on your desired event use this
document.getElementById('<%= lblError.ClientID %>').style.display = ""; or
document.getElementById('<%= lblError.ClientID %>').style.display = "block"
ok then try this, instead of client side, make it serverside. First set it invisible like , on formload event set invisible using lblEror.visible = false and remove style ="display:none" from html.
Then on the desired event/s make it visible and after processing again invisible.
If you want it strictly thorugh js.try this workaround. remove style from asp label. on body onload make it disable from some js function. now on the btn click event make it visible using the method something like this
function Validate()
{
var objLbl = $get('<%=lblError.ClientID%>');
if (validations fails)
{
objLbl.style.display = ""; //displays label
return false;
}
else
{
objLbl.style.display="none" //hides label
return true;
}
}
<asp:button id="btnValidate" runat="server" onclientclick="return validate();"/>
Hope this will work
Take a look at jquery, you can select by classes instead of id's which will never be altered when rendered onto the page (unlike id's)
Is it possible to pass the contents of a textbox or Listbox into the URL portion of the javascript code window.open(URL)? I have an asp.net listbox control that displays URL values. When ever an end user clicks on another listbox, the URL listbox provides the specific URL. I am trying to pass this URL into the above javascript code, but I do not know the correct syntax to do this. This code will execute as an onclick event.
For clarification, similar to typing “+ ListBox.Text.ToString() +” or ‘” & List.Text & “’” to add the content of a listbox into something else, such as a textbox. Is there specific syntax to do the same, but add the listbox.text into javascript?
Thank you,
DFM
Simply add a client-side onclick handler to your listbox as shown below:
<asp:ListBox id="ListBox1" runat="server" .....
onclick="openPopup(this)">
........
</asp:ListBox>
Then add the following javascript code:
<script type="text/javascript">
function openPopup(e){
window.open(e.value);
}
</script>
Sure, this should be pretty easy with jQuery. Obviously the URL generation could be reduced to a single statement, but should give you the general idea.
$(document).ready(function() {
$("your-element").click(function() {
var str = $("#listbox-id").val();
var url = "your-url.com/" + str;
window.open(url);
});
});
ASP.NET 2.0, testing in FF3 and IE7.
When I hit the 'enter' button from a text box the corresponding "OnClick" event for the first ImageButton in the page is fired. If I remove that image button, it fires the next ImageButton OnClick event on the page.
From the FireBug console, if I use JavaScript to submit the Form, this does not happen. But for whatever reason hitting enter from the textbox triggers the unrelated ImageButton event.
I found this question which had a similar problem, however the proposed answer to that solution doesn't work since ImageButtons do not have a "UseSubmitBehavior" property on them.
I don't understand why this event is firing. If I look at Request.Form, I can see that __EVENTTARGET is empty, and it is in fact posting the entire form contents (all of my textboxes), but also includes imageButton.x and imageButton.y key/value pairs.
Why is this? I suppose I could detect "enter" key presses from these text boxes with javascript, but my experience in the past is this behavior is highly variable between browsers. Any suggestions?
here's a more elegant solution
<asp:TextBox ID="TextBox1" runat="server"
onkeydown = "return (event.keyCode!=13);" >
</asp:TextBox>
read the entire post here
You could try setting a default button in an asp panel or on your form. This will let you control what happens when a user hits the enter key.
I'm having the same issue on my project.
This issue is caused because ASP.NET always will assume that the first element that inherits from IButton interface (Button and ImageButton) is the default button from the page.
Hipoteticaly, if you use an LinkButton instead of Button or ImageButton, this issue is solved.
You can find more information here on MSDN.
You can disable the Enter key from being pressed, so the user will have to click on of your ImageButtons. Just paste this javascript block onto your page:
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
Recently, I've been doing more on the client with web services and fewer postbacks. By moving my controls outside of the form element (or eliminating it altogether), the problem goes away. It's inserted by default on aspx pages, but it didn't occur to me until recently that I don't need it for much of what I do.
Its the default behaviour for an enter button press in a non text area to post back a form. You would have to handle it in a javascript method to stop the postback.
You'd just need to check the window.event.keyCode property to see if its equal to 13. If it is, reset it to 0.
function KeyPress()
{
if (window.event.keyCode == 13)
{
window.event.keyCode = 0;
}
}
I suppose I could detect "enter" key presses from these text boxes with javascript
That's what I did to get around that behaviour and it works great in IE7 and FF3. It's just a little unnatural.
Here is a generic exemple:
function TextBox1_KeyDown(sender, e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if(key == 13 && $("#TextBox1").val() != "")
{
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("TextBox1", "", true, "", "", false, true));
}
return (key != 13);
}
I used WebForm_DoPostBackWithOptions because I needed validators to trigger. Otherwise, you might want to use __DoPostBack.
Here are the "prototypes":
function __doPostBack(eventTarget, eventArgument)
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit)
{
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options)
Hope it helps.
P.S.: I used JQuery here but $get would be the same.
Here's an elegant solution I have found, in case anybody else has this problem (in case all other solution don't work for you, as they didn't work for me):
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Panel runat="server" DefaultButton="doNothingButton">
<ul id="shopping-list-ul">
</ul>
<asp:Button CssClass="invisible" runat="server" ID="doNothingButton" OnClientClick="return false;" />
</asp:Panel>
</ContentTemplate>
The textbox iself was inside the ul (generated by javascript).
Pressing enter will trigger the "doNothingButton", which will return false on client side, causing no postback at all!
A TextBox is set to AutoPostback as changing the value should cause a number of (display-only) fields to be recalculated and displayed.
That works fine.
However, when the field is tabbed out of, the focus briefly moves on to the next field, then disappears when the page is redrawn so there is no focus anywhere.
I want the focus to be on the new field, not the textbox I've just changed.
Is there a way to work out which field had the focus and force it to have it again when the page is redrawn?
This is "by design". If you are using ASP.NET 2.0+ you can try calling the Focus method of your TextBox once the postback occurs (preferably in the TextChanged event of the TextBox).
I am not sure if there is any built-in way to track focus but I found this article in CodeProject which should do the trick.
You could also consider refresh display-only fields using AJAX UpdatePanel. This way you won't lose focus from the new field.
Also I have proposed pure server-side solution based on WebControl.Controls.TabIndex analysis, you can use it, if you like.
This is what is happening:
1) TAB on a field - client event
2) Focus on next field - client event
3) Postback - server event
4) Page redrawn - client event new page overrides preious client events
The solution of your problem is to:
a) get the element that has gained focus BEFORE postback
<script>
var idSelected;
$("input").focusin(function () {
idSelected = this.id;
});
</script>
b) store the ClientID (actually in var idSelected) somewhere (i.e. an hidden Textbox, vith ViewState = true) BEFORE postback
** b) get ClientID ** (extract from hidden TextBox and put it in var idSelected) AFTER postback
d) get the element with ClientID and set focus AFTER postback
<script>
$(document).ready(function () {
if (idSelected != null) {
$("#" + idSelected).focus();
idSelected = null;
});
});
</script>
Note: this sample scripts use JQuery.
Remember to put Jquery.js in your solution and a reference in your page
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<asp:ScriptManager runat="server" >
<Scripts>
<asp:ScriptReference Path="~/Scripts/jquery.js" ScriptMode="Auto" />
....
Note2: this solution works without AJAX.
Look at this answer: to make Javascript work over Ajax you must use code like this:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args)
{
MyScript();
}
</script>