Textbox Onclick = clear value , on exit from textbox set the default value? - c#

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.

Related

Detect which button is clicked in Page_Load?

In my asp.net web page, there are a few of buttons and checkboxs. They all can cause postback.
Can I detect which control is clicked? Because I will add code for if clicked a button then do something.
I saw that some examples are done with Jquery.
Can we just do it in C#?
Thanks.
Why are you not just using the click behavior of the button:
ASPX
<asp:Button id="Button1"
Text="Click here for greeting..."
OnClick="GreetingBtn_Click"
runat="server"/>
CS
void GreetingBtn_Click(Object sender,EventArgs e)
{
}
reference here
You could check Request.Form["_EVENTTARGET"] for the control that generated the postback
well if each of the buttons submit a key value to the post or get parameters, and theyre all different it should be pretty easy! :)
localhost/home.html?button=clicked&link=selected
the above is an example of a get parameter url, you can use jquery to get those, or if its a post you would have access to them in a similar way...the previous page would have to have been a form though.
You could eventually do it by checking Request.Form["_EVENTTARGET"] but that is highly unusual and certainly not necessary.
Whatever you need to do, you can do it in the Click event handler of the given control.
You can set a server hidden control specifying the action (checkbox/textbox/button clicked) using javascript & retrieve that server control in page load to check its action & add your code for that action

How to submit a form without postback in asp.net?

I have a form in asp.net webpage which contains 2 drop down lists and a hyperlink + a button.
I want that if user changes an option is dropdowns to change navigate url.
I have done like so:
<asp:DropDownList ID="ddlPackages" AutoPostBack ="true" runat="server"
onselectedindexchanged="ddlPackages_SelectedIndexChanged"></asp:DropDownList>
and then I have the method defined.
The point is that I don't want to make a submit when I change the drop down. Can I do it using only aspx or I have to use javascript?
If I understand you correctly you want to change the href of the hyperlink based on the selected value of the dropdown. You can do this with javascript. Make sure you have AutoPostBack="false" and remove the OnSelectedIndexChanged attribute as well.
To do it using jQuery, use something like this:
<script type="text/javascript>
$(function(){
var $dropdown = $('#<%= ddlPackages.ClientId %>');
$dropdown.change(function(){
//Put logic to decide the link here based on the select value
var newPage = 'page' + $dropdown.val() + '.aspx';
$('#linkId').attr('href', newPage);
});
});
</script>
Edit:
In case you absolutely must have the logic for getting the new url based on the drop down value on the server side, you can turn the method into a Page Method and call it using ajax from the jQuery script above. But you can probably get away with creating the javascript dynamically in the aspx page instead.
I see two options:
1) Wrap the controls in an Update Panel (.NET 3+). Put AutoPostBack=true on the dropdownlist, and define a SelectedIndexChange event for it that changes the hyperlink control's Navigate URL property. When the user changes the dropdown, you're method will fire without the APPEARANCE of a form submission. Downside: there's a slight delay between the dropdown changing and the link changing. If your server is really, really slow, this delay could potentially cause problems (but this is probably unlikely).
2) Use custom JavaScript and do away with your .NET controls completely. This is what I would probably do, assuming you don't need to do anything else with these controls programatically. Your JavaScript function would monitor the dropdown for a SelectedINdexChange and adjust the href attribute of the anchor tag accordingly. Look into jQuery to speed up development if you aren't too familiar with plain JavaScript.
If the control is an ASP:DropDownList, you can use the AutoPostBack="True|False" property to prevent a postback
If you don't want to use the AutoPostBack you have to post the form using jQuery or Javascript
You can add an event on your drop down list onchange and add the code you need to post the form usin jQuery:
$('#formId').submit();
http://api.jquery.com/submit/
If you to want navigate to another Url add the below code at your DropDownList control (make sure AutoPostBack=false)
onchange="window.location.href='yourUrl'"
it would be better put that Javascript on a separate file anyway

WebBrowser Control update hidden field

I am trying to change the value on a hidden field in a WebBrowser control.
I can inject Javascript that displays an alert box. I can make the alert box show the current value of the hidden field. However, I cannot get the value of the hidden field to change.
I have tried changing the value by doing this (tb is the WebBrowser control):
HtmlElement head = tb.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = tb.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function DoIt() { document.getElementById('TestHiddenField').value='Hello World'; alert('Updated'); }";
head.AppendChild(scriptEl);
tb.Document.InvokeScript("DoIt");
In the above the alert does pop up.
And I have tried this:
tb.Document.Body.InnerHtml = tb.Document.Body.InnerHtml.Replace("MyValue", "YourValue");
In the above I see that the InnerHtml does change when debugging.
However, when the page is done loading and I view source the value is never changed.
Also, Even though I can inject javascript to and it pops up the alert, I am never able to find the javascript int the code.
What's going on? What am I doing wrong?
Thanks!
UPDATES:
I'm doing this in the DocumentCompleted event.
I'm not using ViewState
ANOTHER UPDATE:
I added another field. This time a non-hidden text field.
<input type="hidden" id="TestHiddenField" value="MyValue" name="TestHiddenField" />
<input type="text" id="TestField" value="MyValue" name="TestField" />
Here is what happens when I do this:
tb.Document.Body.InnerHtml = tb.Document.Body.InnerHtml.Replace("MyValue", "YourValue");
When the page renders in the WebBrowser Control the text box displays the text "YourValue" but when I View Source the value still equals "MyValue".
What's up with that? I need for it to equal "YourValue".
Any ideas?
Thanks again!
However, when the page is done loading and I view source the value is never changed.
Do not alter the DOM until after the page is done loading. You have to wait for the DocumentCompleted event to fire.
Since this is server side code, you should use an ASP.NET control and simply change the value. If I was to take a guess what is wrong, it most likely deals with one of two things:
you are setting the value before you set the "initial value" in your code. Since you do not have events listed, I have no clue if this is correct.
You are using viewstate and the viewstate value is overwriting, as you are going through a rather heavy way of changing values.
If you want to see where things are happening, consider adding all page events and set breakpoints and watch the value of the control. You will find, rather quickly, where things are happening.

Removing default text from text box

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.

Text inside a text box that must be cleared when clicked

I am using ASP.NET.
I am not sure what you will call this but I would like text to be displayed in my text box called txtName. So when the form load the text box will have faded text that will say "Required". Then when the user click inside the text box i want the user to place a value inside the text box.
Is this possible in ASP.NET? If so, how can this be done????
If you can use the MS AjaxControlToolkit, there is a watermark extender that will do precisely that.
MS Ajax TextBoxWatermark Extender
If not, you can probably find a jQuery plugin or roll your own javascript. Using server-side events will probably not do what you want.
onClick is a client side event. onFocus may be better. You can use
txtName.Attributes.Add("onFocus", "this.value = '';this.style.color = 'black';")
Put it in the Page's PreRender event.
Here's a great jQuery plug-in:
http://www.mudaimemo.com/p/formnotifier/
Try something like this:
<asp:TextBox ID="txtName" runat="server"
onclick="if (this.value == 'Required') {this.value=''}"
Width="275px">Required</asp:TextBox>
If using the Ajax Toolkit is an option or makes sense there is a tool in the tool box called textbox watermark (see http://www.asp.net/AJAX/AjaxControlToolkit/Samples/TextBoxWatermark/TextBoxWatermark.aspx)

Categories