I have a textbox which is extended by an Ajax Control Toolkit calendar.
I want to make it so that the user cannot edit the textbox and will have to instead use the calendar extender for input.
I have managed to block all keys except backspace!
This is what I have so far:
<asp:TextBox ID="TextBox1" runat="server" onKeyPress="javascript: return false;" onKeyDown="javascript: return false;" onPaste="javascript: return false;" />
How would I also disable backspace within the textbox using javascript?
EDIT
Made an edit since I need a solution in javascript.
EDIT
It turns out that onKeyDown="javascript: return false;" DOES work. I have no idea why it wasn't working before. I tried using a new textbox and it blocked backspaces fine. So sorry to everyone who posted an answer hoping to get some rep esp. after I marked it for bounty.
My textboxes now (seem) to block ALL keystrokes and also still work with the calendar extender.
ZX12R was close. This is the correct solution:
The TextBox is like this:
<asp:TextBox ID="TextBox1" runat="server" onKeyDown="preventBackspace();"></asp:TextBox>
and the script looks like this:
<script type="text/javascript">
function preventBackspace(e) {
var evt = e || window.event;
if (evt) {
var keyCode = evt.charCode || evt.keyCode;
if (keyCode === 8) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
}
}
</script>
First of all, the backspace wont come through on Key Press, so you have to use Key Down.
Can't you just use the HTML readonly="readonly" attribute?
<input type="text" name="country" value="Norway" readonly="readonly" />
<textarea rows="3" cols="25" readonly="readonly">
It should work! :)
</textarea>
How about using a label for the display and a hidden textbox to get the value back to the server?
You need to apply readonly on the client side controller ONLY, so that asp.net doesn't see it and still reads the data on postback. You can do this several ways, one of the easier if you use jQuery is to add a class to the text-boxes eg. cssclass="readonly" in question and $(".readonly").attr("readonly", true);.
As others said ReadOnly="True" will break the postback mechanism.
I believe you can get around it in your code-behind by accessing the Request object directly during PageLoad:
//assuming your textbox ID is 'txtDate'
if(Page.IsPostBack)
{
this.txtDate.Text = Request[this.txtDate.UniqueID];
}
Your other option is to allow Disabled controls to postback on the form, but this is somewhat of a security concern as readonly fields modified via script could potentially come back:
<form id="MyForm" runat="server" SubmitDisabledControls="True">
..
</form>
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.submitdisabledcontrols.aspx
I'm not sure the impact of this property on ReadOnly (vs Enabled="False") controls but it's worth trying.
And finally - I did run into the same issue you're having a few years ago, and from what I remember there is a difference between using an html input marked as readonly and runat="server", and an actual serverside control where ReadOnly="true".
I have a feeling doing:
<input type="text" readonly="readonly" runat="server" id="myTextBox" />
may have still allowed the data to come through, although in the code-behind you have to treat the control as a HtmlInputText or HtmlGenericControl vs. a TextBox. You can still access the properties you need though.
Just a few ideas anyway...
here is a possible solution... add an event listener...
<asp:TextBox ID="TextBox1" runat="server" onKeyPress="KeyCheck;" />
and then the function can be like this..
function KeyCheck(e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
if (KeyID == 8 ) {
alert('no backspaces!!);
}
}
doubt if it has to be onkeypress or onkeyup...
ReadOnly attribute does not help. The backspace still is taking your browser to back page even if your text box is read only..
use regular text boxes not read-only and not Disabled, just use client-side JavaScript to ignore keypresses.
This will ignore all keypress so you will have your READONLY behaviour and it will also ignore the backspace.
<input type="text" value="Your Text Here" onkeydown="return false;" />
No Need to call any function and all just try this:
<asp:TextBox runat="server" ID="txt" onkeydown="return false;"
onpaste = "return false;" onkeypress="return false;" />
I was able to do something similar, with Jquery. Just putting it out here for reference!
$("#inputID").keypress(function (e)
{e.preventDefault();});
$("#inputID").keydown(function (e)
{e.preventDefault();});
the first prevents keypresses, while the second prevents key down events.
Still a JS noob, so feel free to point out good / bad things with this.
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.
I have a role called 'member' and another 'admin' in Asp.Net website.
I did before, that button should be visible or not and i am successful in that,but,i am not able to get the proper code(aspx.cs) to disable the button so that it may be in view but not at all accessible.
<asp:Button ID="Button4" runat="server" PostBackUrl="~/report.aspx"
Text="print in report format" Width="173px"
Enabled='<%# HttpContext.Current.User.IsInRole("Admin") %>' />
i want that whenever a member login then button "report" should be disabled for him.
You have to set the Button.Enabled property value to according to the HttpContext.Current.User.IsInRole("admin") function returned value.
Either in html:
<Button ... Enabled='<%# HttpContext.Current.User.IsInRole("Admin") %>' ... >
Or in code behind:
Button.Enabled = HttpContext.Current.User.IsInRole("Admin");
if (HttpContext.Current.User.IsInRole("member"))
{
//enable/disable here
}
In the Page_Load after checking for the role you may be able to set the IsEnabled for the Button to be False.
e.g. buttonLogin.Enabled = (IsUserInRole(Admin));
Either I'm missing something or the solution is simply:
button.Enabled = false;
I'm assuming you are using an ASP.NET button control - if you are then you need to set the Visible and Enabled button properties to false
The primary problem you have here is the hash mark: <%# is used to identify a binding. Unless you're calling this in a gridview or a formview or something, this will not work. I would recommend setting it in the code behind as suggested by #Muhammad Akhtar, but if you're hell bent for leather on using the html side it should probably be:
Enabled='<%= HttpContext.Current.User.IsInRole("Admin").ToString() %>'
i m working on simple asp.net and in that i am using validators.
my situation is like that i have used reaquired field validator its working fine.
and after that if i ented data and fired insert query then data is inserted and sucessful message is displyed on the lable. but agin if i clik on submit button with empty fields then validator works but the lable of successful message does not disapper. how to hide that lable.
You need to use javascript to hide the success message, here is a sample
<script type="text/javascript">
function hide() {
document.getElementById('<%=lblSuccess.ClientID %>').style.display = 'none';
return false;
}
</script>
<asp:Label ID="lblSuccess" runat="server" Text="Success"></asp:Label>
..your form code
<asp:Button ID="btnOk" runat="server" Text="OK" OnClientClick="hide()" ValidationGroup="ValidateForm" />
Why javascript, the form doesn't get posted because validators don't let the form to be posted if the conditions aren't met, so you are left to hide the message dynamically with javascript
<script type="text/javascript">
function Hide() {
document.getElementById("Lable1").style.display = 'none';
return false;
}
</script>
<asp:Button ID="Button1" OnClientClick="Hide()" runat="server" onclick="Button1_Click" Text="Button"/>
and use
if (Page.IsValid){}
on clik event.
Show us some code of what you're up to and we can tell you more precisely where you are going wrong. In a nutshell though the visibility of that message is going to be persisted through a postback so you have to explicitly tell it to not be visible if validation has failed.
Set the label to visable=false and on save set the text value if required and change visible =true ?
On form load, do something like this:
TheValidMessageLabel.Visible = Page.IsValid;
You are probably just setting the visible state to true when it's valid and never setting it to false again.
Set your success label visibility in page load to false.
And only if operation is successfully set that label visibility to true.
cheers
How can I get gridview HTML textbox value in .aspx.cs code?? E.g. :
<input id="Frequency" name="customerName" type="text" style="width: 44px" />
If i use the bellow code ,Then i can get the value on selectedIndex event.
string n = String.Format("{0}", Request.QueryString['customerName']);
I want to use bellow syntax.
TextBox_Label1 = (TextBox)e.Row.FindControl("Frequency");
i don't want to user the runat="server" on HTML control .
From Gridview i need to call a popup,Popup return a value ,I use the bellow code on javascript to do that
window.opener.document.getElementById("customerName").value = val;
window.close();
In my gridview .if i put the runat="server" then return value not set ,So i need to remove the runat="server".It also not work if i put the Asp:TextBox on Grid.Help me to Return popup value on gridview Asp:TextBox
Thanks!
Try a databinding expression:
<input id="Frequency" name="customerName" type="text" style="width: 44px"><%# String.Format("{0}", Request.QueryString["customerName"])%></input>
If you're having problems with this process and the difference is one is runat="server" and the other is not, I would suggest you need to look at your JavaScript to make sure that you have the proper element selection method. The rendered ClientID will be different from a standard html control ID. If you write your code so that the ClientID is injected into the JavaScript, you can keep the runat="server" and achieve your results. Standard html controls are not accessible from the code behind.
i have a series of rows that are generated using an asp:repeater:
<asp:repeater ID="itemsRepeater"
OnItemDataBound="itemsRepeater_ItemDataBound"
runat="Server">
<itemtemplate>
<tr>
<td>
<asp:HyperLink ID="linkView" runat="server"
Text="<%# GetItemText((Item)Container.DataItem) %>"
NavigateUrl="<%# GetViewItemUrl((Item)Container.DataItem) %>" />
</td>
<td>
<asp:HyperLink ID="linkDelete" runat="server"
Text="Delete"
NavigateUrl="<%# GetDeleteUrl((ActionItem)Container.DataItem) %>" />
</td>
</tr>
</itemtemplate>
</asp:repeater>
The repeater creates an HTML table, with each row containing a link to an item and (what is essentially) a "Delete" link. The above simplified example code generates HTML similar to:
<TR>
<TD>
<A href="ViewItem.aspx?ItemGuid={19a149db-5675-4eee-835d-3d78372ca6f9}">
AllisonAngle_SoccerGirl001.jpg
</A>
</TD>
<TD>
Delete
</TD>
</TR>
Now that all works, but i want to convert the "Delete" to client side. i want to be able click the link and it will, on the client javascript:
prompt an alert "Are you sure..."
have javascript issue server-hit to actually delete the item they want
remove the item from the client DOM tree
So there are four problems to be solved:
How to hook up javascript to the client-side click of the Delete link.
How to know what item the user clicked Delete
Prevent a post-back
Delete the row that the user clicked
That is my question.
From here on you will find my rambling attempts to solve it. Don't take anything below as relating in any way to any possible accepted solution. Just because i posted code below, doesn't mean any of it is useful. And it doesn't mean i'm anywhere within spitting distance of the best solution. And because i can't make anything below work - it must have gone down the wrong road.
My Attempts
Wiring Up Javascript
The first task is to convert the delete link HTML from something such as:
<A href="DeleteItem.aspx?ItemGuid={19a149db-5675-4eee-835d-3d78372ca6f9}">
Delete
</A>
into something more javascripty:
<A href="#"
onclick="DeleteItem('DeleteItem.aspx?ItemGuid={19a149db-5675-4eee-835d-3d78372ca6f9}')">
Delete
</A>
and the add the script:
<script type="text/javascript">
//<![CDATA[
function DeleteItem(deleteUrl)
{
//Ask the user if they really want to
if (!confirm("Are you sure you want to delete INSERT NAME HERE?"))
{
return false;
}
//Call returns false if the server returned anything other than OK
if (!DoAjaxHit(deleteUrl)
{
return false;
}
//Remove the table row from the browser
var tableRow = document.getElementById("TODO-WHAT ID");
if (row != null)
{
//TODO: how to delete the tableRow from the DOM tree?
//document.Delete(tableRow) ?
}
//return false to prevent a postback
return false;
}
//]]>
</script>
What combination of ASP code can be used to create the above? i hear that asp:LinkButton has an OnClientClick event, where you can wire up a javascript function:
<asp:LinkButton ID="linkDelete" runat="server"
Text="Delete"
OnClientClick="DeleteItem(<%# GetDeleteUrl((ActionItem)Container.DataItem) %>);"/>
Problem is that the rendered HTML is literally containing:
<a onclick="DeleteItem(<%# GetDeleteUrl((ActionItem)Container.DataItem)) %>);" ...>
Delete
</a>
If i change the client click event handler to:
OnClientClick="DeleteItem('todo - figure this out');"/>
it works - as well as "todo - figure this out" can work.
Preventing Postbacks
The dummied down above javascript call actually happens (i can see my alert), but there's the next problem: Returning false from the javascript function doesn't prevent a postback. In fact, i can see that the href on the generated html code isn't "#", but rather
javascript:__doPostBack('ctl0....
i tried changing the ASPX code to include the OnClick handler myself:
OnClick="#"
OnClientClick="DeleteItem('todo - figure this out');"
But the compiler thinks the pound side is a pragma, and whines:
Preprocessor directives must appear as
the first non-whitespace character on
a line
Table Row Identity
The table rows don't have an ID, they're generated by the asp:repeater.
How can the javascript function know what triggered the click event? The javascript needs to be able to find the element, and remove it from the tree.
Note: i would of course prefer fade+collapse animation.
Normally you get an element by using
var tr = document.getElementById("the table row's id");
But the table rows don't have an easily knowable ID. Since there are multiple rows, the server generates the ID as it builds the table. i realize some solution is going to have to involve changing:
<TR>
into
<TR runat="server">
so that there will be server generated identity for each table row, but how do i reference the generated name from javsscript?
Normally i would have thought that the scripting problem would be solved by using multiple paramters:
function DeleteItem(tableRowElement, deleteUrl)
{
//Do a web-hit of deleteUrl to delete the item
//remove tableRowElement DOM object from the document tree
}
But the problem is just pushed elsewhere: How do you populate tableRowElement and deleteUrl for the call to the javascript function?
Such a simple problem: convert a click from a postback to client-side.
The volume of problems involved is getting quite idiotic. Which seems to indicate that either
the idea solution is something completely different
there is no solution
References
Stackoverflow: How do I fade a row out before postback?
Stackoverflow: Javascript before asp:ButtonField click
asp.net: Accessing repeater elements from javascript.
Stackoverflow: How to access repeater generated elements?
jQuery can dig out the tags for you:
$("[id$=linkDelete]").click(function() {
DeleteItem(this.href);
});
That code says "find all the DOM elements whose ID ends with 'linkDelete' and wire up the following click event handler".
I would recommend against implementing the Delete function through links in this way. Delete links are a security risk.
Rather, it's better to require a post to that url instead. If you want to be doing ajax, I would strongly recommend using a javascript framework so you don't have to deal with the differences in how different browsers implement XmlHttpRequests.
For instance, in jQuery you could do it like this:
$.post('Delete.aspx',{itemGuid:'{19a149db-5675-4eee-835d-3d78372ca6f9}'},
function(data, textStatus) {
if (textStatus == 'success') {
$(this).parents('tr:eq(0)').fadeOut();
}
});
which would do both the ajax call and the fadeout effect you want.
You could then access the item guid in Delete.aspx from Request.Form["itemGuid"], and this wouldn't be vulnerable to link attacks.
Preventing Postbacks
The server is generating a postback wireup because you're using a server control. Use a plain <a> tag without a runat='server' directive.
Table Row Identity
I usually do this by databinding an ID column of some kind and putting this in the repeater template:
<tr id='<%#Eval("ID")%>'>
P.S. I hate to sound like a fanboy, but jQuery will make all of these things an order of magnitude easier. You should really consider it if you can. Otherwise, you're going to be in a world of hurt trying to implement these features in a consistent way across browsers.
P.P.S. If the Delete.aspx and similar urls are only going to be called from javascript, I would recommend using ashx http handlers instead. You can do all of the same server logic without the needless overhead of a full-blown page.
mine usually comes out looking like
<asp:LinkButton runat="server" OnClientClick='<%# Eval("ID", "DeleteItem(this, \"{0}\"); return false;") %>' Text="Delete" />
that will make html that looks like
<a id="blah_blah_ctl01" onclick='DeleteItem(this, "{19a149db-5675-4eee-835d-3d78372ca6f9}"); return false;'>Delete</a>
I include the "this" reference so that you can have access to the dom and delete the link...or it's parent or whatever. From there it's pretty straight forward to use jQuery to actually do the posting and DOM manipulation. The "return false;" disables the postback.
The other answerers found various bits related to different aspects of the question. i managed to cobble together a complete solution. i've copy/pasted the relavent snippits here.
The first important change is the use of an asp:LinkButton which allows as OnClientClick event, which gives you direct access to the javascript OnClick event:
<asp:repeater ID="itemsRepeater"
OnItemDataBound="itemsRepeater_ItemDataBound"
runat="Server">
<itemtemplate>
<tr>
<td>
<asp:HyperLink ID="linkView" runat="server"
Text="<%# GetItemText((Item)Container.DataItem) %>"
NavigateUrl="<%# GetViewItemUrl((Item)Container.DataItem) %>" />
</td>
<td>
<asp:LinkButton ID="linkImpregnate" runat="server"
Text="Impregnate"
OnClientClick="<%# GetImpregnateUrl((Item)Container.DataItem) %>" />
</td>
</tr>
</itemtemplate>
</asp:repeater>
The code-behind manually builds presentation code (yay for separation of controller and view!) that contains a javascript call.
protected string GetNodeAcknowledgementClientClick(Item item)
{
if (!(item is HotGirl))
return ""; //this shouldn't be called for non-acknowledgements, but i won't fail
HotGirl girl = (HotGirl)item;
String szOnClientClick =
"return ImpregnateGirl(this, "+
Toolkit.QuotedStr(girl.GirlGUID.ToString()) + ", "+
Toolkit.QuotedStr(GetItemName(item))+");";
return szOnClientClick;
}
And finally in the aspx, i find a random spot to mash in some javascript:
<script type="text/javascript" src="Javascript/jquery.js"></script>
<script type="text/javascript">
//<![CDATA[
function DeleteItem(sender, girlGuid, girlName)
{
if (!confirm("Are you sure you want to impregnate "+girlName+"?"))
{
return false;
}
$.post(
'ImpregnateGirl.aspx?GirlGUID='+nodeGuid,
function(data, textStatus) {
if (textStatus == 'success')
{
$(sender).parents('tr:eq(0)').hide();
}
else
{
return false;
}
}
);
//return false to suppress the postback
return false;
}
//]]>
</script>
i would have made the jQuery do a post, as a security measure as guy suggested, but jQuery would give an error, rather than posting. Rather than care i chose to not care.