I have an ASP.NET TextBox and I want it to be ReadOnly. (The user modify it using another control)
But when there is a PostBack(), The text get reset to an empty string.
I understand that if you set the ReadOnly property to True of a TextBox it's content does not get saved through PostBack().
Is there a way to keep the content after PostBack() and make the TextBox not editable by the user?
I tried to set the Enabled property to False,But still the content doesn't save after PostBack().
Another solution I found and easier one:
Add this to the Page Load method:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("readonly", "readonly");
}
Have your other control store the value in a hidden field, and on postback, pull the value from the hidden field and push it into the textbox on the server side.
txtStartDate.Attributes.Add("readonly", "readonly"); on pageload in the best of the best solutions ,instead or Javascripts,hidden variables,cache,cookies,sessions & Caches.
Get the value using Request.Form[txtDate.UniqueID]. You will get it !!
I've had this same issue but using Knockout binding 'enable' and ASP.Net Server Control Text.
This way:
<asp:TextBox ID="txtCity" runat="server" required="required" class="form-control" placeholder="City" data-bind="value: city, enable: !hasZipCode()"></asp:TextBox>
However, when the form was submitted this field value was always empty. This occurred, I presume, because if the control is disabled, it is not persist on the ViewState chain.
I solved replacing bindig 'enable' by 'attr{ readonly: hasZipCode}'
<asp:TextBox ID="txtCity" runat="server" required="required" class="form-control" placeholder="City" data-bind="attr{ value: city, readonly: hasZipCode }">/asp:TextBox>
Here is a way to do it with javascript in the onfocus event of the Textbox itself.
Doing it like this with javascript has the advantage that you don't need to do it in code behind, which can be difficult if you need to do it in gridviews or similar.
This javascript code is only tested on Internet Explorer and certain parts of it will only work on IE, like for example the createTextRange part which is there just to make the caret end up at the beginning of the text in the Textbox, but that part can be skipped if not needed.
If the core of this technique works on other browsers then it should be possible to make the code cross browser. The core of the idea here is the blur after setting readonly and then a timeout to set the focus again.
If you only set readonly then it does not become readonly until next time you give the Textbox focus.
And of course, the code can be put into a function instead which is called with "this" as argument.
<asp:TextBox
ID="txtSomething"
runat="server"
Text='<%# Bind("someData") %>'
onfocus="
var rng = this.createTextRange();
rng.collapse();
rng.select();
if (this.allowFocusevent=='0') {return;};
this.allowFocusevent='0';
this.readOnly=true;
this.blur();
var that=this;
setTimeout(function(){that.focus()},0);
"
/>
Set the ContentEditable property of textbox to false ContentEditable="false"..
It wont allow you to edit the contents of the textbox
ie;will make the textbox readonly and
also will make the value stay in the textbox after postback..
I think its the easiest way to do it..
Related
I'm writing an application in C#. I would like to replace the value for the TEXT property after the user clicks (focuses) on a textbox. I would like to set the TEXT value to be blank instead of the words "ENTER NAME HERE" when they click to edit the textbox.
Front-end:
<asp:TextBox Text="ENTER NAME HERE" OnClick="MyTextboxID_OnClick" ID="MyTextboxID" runat="server"></asp:TextBox>
Code-behind:
protected void MyTextboxID_OnClick(object sender, EventArgs e)
{
MyTextboxID.Text = "";
}
I tried to find the answer to this question but the answers didn't quite match what I wanted to do.
I was hoping C# had something similar to Javascript's "OnClick" or "OnFocus" events. I added the OnClick event to the textbox for illustration purposes. This OnClick event doesn't work.
Thank you in advance for your help!
Remember that ASP.NET is primarly server-side. Actions that run in C# require a post-back to the server. The impact of this on a page can be mitigated somewhat by using AJAX, but this is why you don't see an "OnClick" event off the ASP control.
However, you can still use the Javascript "OnClick" event. Since Javascript runs on the client, and the interaction in this instance is entirely handled on the client, you should just use that.
If you are not comfortable using Javascript, you might want to look at TextBoxWatermark server side control.
It is available NuGet.
<asp:TextBox OnClick="MyTextboxID_OnClick"
ID="MyTextboxID" runat="server">
</asp:TextBox>
<ajaxToolkit:TextBoxWatermarkExtender ID="TBWE2" runat="server"
TargetControlID="MyTextboxID"
WatermarkText="ENTER NAME HERE"
WatermarkCssClass="watermarked" />
You should simply use the following Placeholder="Enter text here."
Option One:
<asp:Textbox id="txtName" runat="server" placeholder="Enter name here." />
Option Two:
$("#<%= txtName.ClientId %>").setAttribute('placeholder', 'Enter name here.');
$("#<%= txtName.ClientId %>").attr('placeholder', 'Enter name here.');
For the Javascript implementation, you would simply place that in your View and wrap it in: <script type="text/javascript"></script>. Those are the ideal approaches to display text which clears on focus.
You could also utilize the Tooltip. Hopefully these examples assist you. Important note, I have no issues with compatibility in IE 8 with the Placeholder. Also these approaches won't force a Postback which can occur due to Server-Side. Which would force you to either do a Postback or implement a Update Panel / Ajax to hide the Postback.
Plugin: https://github.com/mathiasbynens/jquery-placeholder
Why don't you use the place holder attribute and not have to worry about replacing the text at all. This would show when the text box is empty but disappear on focus
I have a web form that allows the user to modify data in certain fields (mostly TextBox controls, with a couple of CheckBox, DropDownList, and one RadioButtonList control) with a submit button to save the changes. Pretty standard stuff. The catch is, I need to keep track of which fields they modified. So I'm using ASP.NET HiddenField controls to store the original value and then on submit comparing that to the value of the corresponding TextBox (for example) control to determine which fields have been modified.
However, when I submit the form and do the comparison, the value of the TextBox control in the code behind still reflects the original value, even though I have changed the contents of the TextBox, so it isn't registering the change. Here is an example of a set of TextBox/HiddenField pairings (in this case last, first, middle names) in my ASP.NET form:
<div id="editName" class="editField" style="display: none">
<asp:TextBox ID="tbxLName" runat="server" class="editable"></asp:TextBox>,
<asp:TextBox ID="tbxFName" runat="server" class="editable"></asp:TextBox>
<asp:TextBox ID="tbxMName" runat="server" class="editable"></asp:TextBox>
<asp:HiddenField ID="hdnLName" runat="server" />
<asp:HiddenField ID="hdnFName" runat="server" />
<asp:HiddenField ID="hdnMName" runat="server" />
</div>
I'm setting the original values of all these controls (".Text" for the TextBox controls, ".Value" for the HiddenField controls) on PageLoad in the code behind.
Here's an example of where I'm doing the comparison when I submit the form (I'm adding the field name, old value, and new value to List<string> objects if the values differ):
if (tbxLName.Text != hdnLName.Value)
{
changes.Add("ConsumerLastName");
oldVal.Add(hdnLName.Value);
newVal.Add(tbxLName.Text);
}
But when I enter a new value into the TextBox control and click Submit:
then step through the code in the debugger, it shows me that the value of the control is still the old value:
Why is the comparison happening against the original value of the TextBox even though the new value is there when I click the submit button?
Update: #David gets the credit for this, even though he didn't post it as an answer -- I was forgetting to enclose the method for pre-filling the original values of the controls in a check for IsPostBack; I really should have known better, I've been doing this for quite a while!
Are you checking for IsPostback in Page_Load so you don't overwrite the values sent in the Postback?
Make sure that you are not overwriting your values in the Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
someTextField = "Some Value";
}
}
It took a while for me to get that the Page_Load method works as an "before anything goes" method and not only a method that is being ran when you visit the page with GET.
Make sure you're not overwriting the value for the textbox somewhere in page init or load without checking for the IsPostback flag.
It may happen due to postback. If you code for set textbox not in !isPostBack then put it.
i.e.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
tbxLName.Text="anything";
}
}
I want to get the value of RadButton which is used like checkbox.
<telerik:RadButton ID="RadButtonCheck" runat="server" ButtonType="ToggleButton"
Checked="false" Text="StackOverflow" ToggleType="CheckBox" Enabled="true" AutoPostBack="false">
</telerik:RadButton>
I have read this question and answer and more..
How to get value for checkbox in JQuery?
But
$('#<%=RadButtonCheck.ClientID%>').is(':checked') //always returns false.
How can I get the correct value?
Edited:
Also .attr('checked') attribute returns nothing and it gives error..
The most suitable answer for my question is:
var button = $find("<%= stackoverflow.ClientID%>");
if(button.get_checked())
{
alert("is checked");
}
Just had a look on this page http://demos.telerik.com/aspnet-ajax/button/examples/radiosandcheckboxes/defaultcs.aspx and looking at the rendered html it looks like you can call
$('#<%=RadButtonCheck.ClientID%>').val();
Which should return "Checked" or "Unchecked". It might differ slightly depending on the exact control but as Aristos suggests you need to look at the rendered HTML.
Alternatively use the RAD Controls Client API found here http://demos.telerik.com/aspnet-ajax/button/examples/clientsideapi/defaultcs.aspx and here http://www.telerik.com/help/aspnet-ajax/button-client-side-basics.html in order to access the checked value. I think you need to call .get_checked() method.
All Telerik RadControls have a rich client side API - which includes properties and methods. In your case i assume you want to know on the client side whether the user has checked the RadButton whose toggle type is CheckBox type.
You can listen for the client side OnClientCheckedChanged event. This event will get you the sender i.e. RadButton which was clicked and event args which is of Type radButtonCheckedEventArgs. This contains get_checked() method which will let you know if the checked state is true (meaning checked) or false (meaning not checked). Here is the code snippet to achieve this:
<div>
<telerik:RadButton ID="RadButtonCheck" runat="server"
ButtonType="ToggleButton" Checked="false"
Text="StackOverflow" ToggleType="CheckBox" Enabled="true"
AutoPostBack="false" OnClientCheckedChanged="onClientCheckedChanged">
</telerik:RadButton>
</div>
<script>
function onClientCheckedChanged(sender, args) {
alert(args.get_checked());
}
</script>
Here is the documentation link for the client side event:
http://www.telerik.com/help/aspnet-ajax/button-onclientcheckedchanged.html
Hope this answers your question.
Lohith (Tech Evangelist, Telerik India)
Can you set a name for the radio button and then try to get the checked value by the name? Something like this:
<telerik:RadButton ID="RadButtonCheck" runat="server" ButtonType="ToggleButton" Checked="false" Text="StackOverflow" ToggleType="CheckBox" Enabled="true" AutoPostBack="false" name="myRadio"> </telerik:RadButton>
$('input:radio[name=myRadio]:checked').val();
I have this in the
<asp:TextBox ID="svv" OnClick="this.value=''" runat="server">Hello...</asp:TextBox>
OnClick="this.value=''" // On mouse click in textbox it will deleted the text.
How can I set something like
Unclick"this.defautlvalue"; // something like this.
So, when I click the control it will clear the value, if I exit from the control (for example, clicking another textbox) it will return the default value of the textbox.
Thanks
Specifically with C# .NET WebForms you have a few options.
You can go completely front-end with jquery by doing something like this:
$('selector').blur(function() {
// Make sure you do some validation so it doesn't clear everytime
$('selector').val('My Default Text');
});
Or, if you are using the AJAX Control Toolkit, you can simply use The textbox Watermark Control, which will do exactly what you are talking about just by setting a few properties.
You can also go straight javascript like #m.edmondson explain in his answer.
I think you're looking for onBlur:
<input type="text" id="fname" onblur="upperCase()">
This will call upperCase() when the user leaves the box.
You can attach to the client-side onblur event which is called when the focus of your control changes.
Also worth storing the default value in an attribute on the input so you can refer to it in blur event. Believe in ASP.NET web forms you've got to add that attribute in the code-behind though.
I got this Text box with default value as "First Name" ..Now when I click inside this text box to enter name , this value "First Name" keeps on displaying. What I want is to the text box to clear as soon as I click inside it. What property do I need to set in mt textbox tag ?
[Edit]
ok anything from Telerik that I can use to do that ?
There is not out of the box functionality in TextBox that will accomplish this, but the ASP.Net Ajax Toolkit has a Watermark Extender that will do everything you want.
I have used both, but now personally use a jQuery Watermark Plugin
Either will work just fine, choose based on your needs.
According to the Telerik docs you just have to set the EmptyMessage property on their TextBox control. Demo Page Here
In the code behind, on Page Load you can add the following code to achieve this
TextBox1.Attributes.Add("onClick", "javascript:if(this.value=='First Name'){this.value='';}");
You can use the method suggested by #Josh. If you do not want to use Ajax Toolkit controls or JQuery you could write it on your own using Javascript. Write a function which gets called when the foucs is received by the textbox control. I thik the function is called onfocus or just focus in Javascript.
Hi I just wrote this small function which will achieve your desired result
function clearInputBox(x,prefil){
if(x.value == prefil){
x.value = '';
}
}
Your input box looks like this
<input type='text' value='First Name' onfocus="clearInputBox(this,'First Name')" />
May be this will help you
Taking Shobans advice one step farther, you could add something like this to your Page subclass
protected override void OnInitComplete(EventArgs e)
{
string jsString = "javascript:if(this.value=='" + TextBox1.Text + "'){this.value='';}";
TextBox1.Attributes.Add("onFocus", jsString);
base.OnInitComplete(e);
}
What this will do is, it will always consider that default string is the one this controll contains at esign time (the initial one in your .aspx file), so you wont have to manually change it in codebehind every time you change your .aspx. Remember, that OnIinitComplete fires before any viewstate or postback data has been applied, but after the controlls on your page have been set to their default values.
P.S. As anishMarokey pointed, use onFocus vs onClick, since fields can gain focus without clicks via Tab key.