How to call TextChanged of TextBox WebForm Control - c#

I use TextBox WebForm Control configured like a Bootstrap Datetimepicker.
And I need to initiate server side TextChanged event.
The code I have does not work so it does not call server side part.
HTML
<div class='datepicker input-group date' id='datetimepickerStart'>
<asp:TextBox ID="StartDate" class="form-control dateField" placeholder="Fecha" required runat="server" OnTextChanged="StartDate_TextChanged"></asp:TextBox>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
C#
protected void StartDate_TextChanged(object sender, EventArgs e)
{
// It does not fire :(
}
I try to force this event like this but no joy.
JS
$('#datetimepickerStart').datetimepicker();
$('#datetimepickerStart').datetimepicker().on('dp.change', function (event) {
console.log(event.date);
$('#StartDate').change(); // It does not help
$('#StartDate').html(event.date); // It does not help
});
Any clue how to fix it?

After searching a lot on the Internet I found this solution that worked to me:
$('#datetimepickerStart').datetimepicker().on('dp.change', function (event) {
__doPostBack('<%= Page.ClientID %>');
});
And on the code-behind:
public void RaisePostBackEvent()
{
// Do whatever, maybe call the OnTextChange method.
}
You can even pass some arguments in the like:
__doPostBack('<%= Page.ClientID %>', argument);
and
public void RaisePostBackEvent(string Arg){...}

In order for the TextChanged event to fire when you leave the textbox, you have to set the TextBox control's AutoPostBack property to true.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.autopostback(v=vs.110).aspx
<asp:TextBox ID="StartDate" class="form-control dateField" autopostback="true" placeholder="Fecha" required runat="server" OnTextChanged="StartDate_TextChanged"></asp:TextBox>
You also need to make sure that the name of the event handler for OnTextChanged matches the name of the method in your code (maybe this was just a typo).
Finally, I've found the TextChanged event to be a bit finicky and cause unwanted postbacks, page scrolling, loss of focus, etc., so you may want to consider using a client-side solution (eg. JQuery) instead.

name of method not correct, add autopostback= 'true' to textbox

Change this line to
<asp:TextBox ID="StartDate" class="form-control dateField" placeholder="Fecha" AutoPostBack="True" required runat="server" OnTextChanged="EndDate_TextChanged"></asp:TextBox>
and it will be ok.

Solution is to add ApiController and consume via JQuery what I need.
https://blogs.msdn.microsoft.com/henrikn/2012/02/23/using-asp-net-web-api-with-asp-net-web-forms/

By default ASP.Net page caches all the server control changed events and executes after Postback event.
So override this default by setting Autopostback property of a control to true like below.

Related

ASP textbox calls javascript function

I have a search textbox in asp. And I want it to send request to the server each time the text is changed there. I have a javascript function which sends request but it is not being called each time when I type something in the text box. How can I call javascript function from ASP textbox?
That is my textbox:
<asp:TextBox ID="search" name="Search" runat="server" onchange="javascript:text_changed();"></asp:TextBox>
That is my js function:
function text_changed() {
searchedword = document.getElementById("ContentPlaceHolder1_search").value;
SendRequest();
}
You should use onKeyPress event to call the function.
<asp:TextBox ID="search" name="Search" runat="server" onKeyPress="javascript:text_changed();"></asp:TextBox>
Shivam's answer is right. You can use KeyPress event to get users key strokes with that event.
But i want to inform you, you should not use ASP.NET control ids like that :
document.getElementById("ContentPlaceHolder1_search").value;
Because you'll get errors if you put your textbox somewhere else in html hierarchy, ASP.NET regenerates it's id.
Try that one, instead :
function text_changed(textObj) {
searchedword = textObj.value;
SendRequest();
}
<asp:TextBox ID="search" name="Search" runat="server"
onKeyPress="javascript:text_changed(this);"></asp:TextBox>
The functionality you asking can achieve by
Use onkeyup or onkeydown instead.
This will then run the function when you type or click on the textbox. You can also then detect the keycode of the event, and prevent the function if you dont want it to run for certain keys.
Use the below code
$("#search").keydown(function(){
text_changed();
});
$("#search").keyup(function(){
text_changed();
});
Demo Here
give it a try :)
$("#search").change(function(){
//your ajax codes
});
<script>
function multy(val)
{
alert(val.value+"--"+val.id);
}
</script>
<input id="txtdemo" type="text" onchange="multy(this);"></br>
<input id="txtdemo" type="text" onchange="multy(this);">
</input>
Thanks... :)

How to implement a click event on textbox in ASP.NET?

In my web application I need a functionality so that when users click on textbox to input values, it should make the button and the other fields visible?
I am using the code provided below but, could not get it working.
C#:
protected void TextBox1_Click(object sender, EventArgs e)
{
ButtonSearch.Visible = true;
}
ASP.NET:
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" Visible="False" />
How to accomplish this?
Set AutoPostback="True". This way the event will be fired server-side, and the button will become visible.
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click" AutoPostBack="true"></asp:TextBox>
However, if you only want to toogle visility of a button, you really should considerate javascript. This will save a trip back to the server.
<asp:TextBox onclick="txtBox1_ClientClicked()" ID="TextBox1" runat="server" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" style="display:none;" />
<script type="text/javascript">
function txtBox1_ClientClicked(){
var theButton = document.getElementById('<%=ButtonSearch.ClientID%>');
theButton.style.display = 'block';
}
</script>
You do not need to post back to the server to accomplish your job. You can use client side onFocus event and javascript/jquery, for example.
I know I used an input of type text, and you are using an ASP Control which posts on server, but here is a JSFiddle to get you on the right track: http://jsfiddle.net/Mmjtz/1/
$("<%= ButtonSearch.ClientID %>").click(function(){
$("#TextBox1").show():
});
In this code you need to pass fields ID which you want to visible on the click of button.
Put the textbox inside a div and use the div's onClick event from codebehind. It's not what you asked but it works for me without any errors. Here is a javascript function to implement requested event:
function toggleVisibility()
{
document.getElementById('TextBox1').disabled = true;
/*
...some other code...
*/
}
And of course, you have to define your onclick event at the div definition after implementing this JS function.
<div id="TBdiv" onClick="toggleVisibility()">
<asp:TextBox ID="TextBox1"..../>
</div>
IMPORTANT: Since you now disabled your TextBox from codebehind, you have to enable it in somewhere before you want to use it again. Otherwise you will not see it while the page is running.
jQuery is the perfect solution for your problem. The code would be something like this:
$("#TextBox1").on("click",function(){$("#ButtonSearch").css("visibility", "visible");})
You include the script by adding <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> to the page and then you can add the piece of code above to within <script></script> tags.

How to check whether ASP.NET button is clicked or not on page load

How can I check whether a particular button was clicked or not in ASP.NET?
I think I need to perform some operation on Page_Load. This shouldn't be entering to Button_Click event to find. Is there any way that I can find where it was clicked or not on Client Side and take it to Page_Load?
Background: Basically __EVENTTARGET and __EVENTARGUMENT , These two Hidden controls are added to the HTML source, when ever any autopostback attribute is set to true for any of the web control.
The __EVENTTARGET hidden variable will tell the server ,which control actually does the server side event firing so that the framework can fire the server side event for that control.
The __ EVENTARGUMENT variable is used to provide additional event information if needed by the application, which can be accessed in the server.
So we can easily get the control causing postback using:Request.Params.Get("__EVENTTARGET");
PROBLEM:
The method: Request.Params.Get("__EVENTTARGET"); will work for CheckBoxes, DropDownLists, LinkButtons, etc.. but this does not work for Button controls such as Buttons and ImageButtons
The Button controls and ImageButton controls does not call the __doPostBack function. Because of this, the _EVENTTARGET will always be empty. However, other controls uses javascript function __doPostBack to trigger postback.
So, I will suggest to do something as below. Add an OnClientClick property to the buttons. Also, define a hiddenField in your Markup, whose value will contain the actual button causing postback.
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick = "SetSource(this.id)" />
<asp:ImageButton ID="ImageButton1" runat="server"
OnClientClick = "SetSource(this.id)" />
<asp:HiddenField ID="hidSourceID" runat="server" />
On the OnClientClick property of the Button and ImageButton Call the SetSource JavaScript function
<script type = "text/javascript">
function SetSource(SourceID)
{
var hidSourceID =
document.getElementById("<%=hidSourceID.ClientID%>");
hidSourceID.value = SourceID;
}
</script>
Here onwards, you can very easily check in your Page_Load as to which Control caused postback:
if (IsPostBack)
{
string CtrlName;
CtrlName=hidSourceID.Value;
}
I just got the same trouble, have to do some logic judgement in the Page_Load method to treat different event(which button was clicked).
I realize the arm to get the as the following example.
The front end aspx source code(I have many Buttons with IDs F2, F3, F6, F12.
<Button Style="display: none" ID="F2" runat="server" Text="F2:Cancel" OnClientClick="SeiGyo(this)" OnClick="F2_Click" />
<Button Style="display: none" ID="F3" runat="server" Text="F3:Return" OnClientClick="SeiGyo(this)" OnClick="F3_Click" />
<Button Style="display: none" ID="F6" runat="server" Text="F6:Run" OnClientClick="SeiGyo(this)" OnClick="F6_Click" />
<Button Style="display: none" ID="F12" runat="server" Text="F12:Finish" OnClientClick="SeiGyo(this)" OnClick="F12_Click" />
The back end aspx.cs source code, what I need to do is judge which button was clicked when Page_Load was triggered. It seems a little stupid, but works.
In your situation, the button be clicked will be added into dic. I hope that will be helpful to some one.
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach(var id in new string[]{"F2","F3","F6","F12"})
{
foreach (var key in Request.Params.AllKeys)
{
if (key != null && key.ToString().Contains(id))
dic.Add(id, Request[key.ToString()].ToString());
}
}
The UniqueID of the button will be in Request.Form["__EVENTTARGET"]
This question is already answered at: ASP.NET : Check for click event in page_load
You can try using the hidden field. Make the client side event on the OnclientClick event and try setting the value of hidden field, may be true or false depending on the condition.
And on the page load you can check the value of Hiidden field.
function click()
{
// set the hidden field here
}
And on the page load, simply check the value.
if(HiddenFieldName.Value=="true")
{
//perform the action
}
private bool button1WasClicked = false;
private void button1_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
if ( button1WasClicked== false)
{
//do somthing
}

OnClick Event not firing when I am specifying action url in asp.net

I need to redirect the user to paypal account. But before that I want to collect name and email for that user. So I am using the following code.
<form id="paypalForm" method="post" action="https://www.paypal.com/cgi-bin/webscr"
target="_top" runat="server">
<div>
<label>
Full Name:<span>*</span></label>
<asp:TextBox ID="name" runat="server" CssClass="large form-poshytip" title="Enter your Full Name."></asp:TextBox>
<label>
E-Mail:<span>*</span></label>
<asp:TextBox ID="email" runat="server" CssClass="large form-poshytip" title="Enter Email Address."></asp:TextBox>
<input type="hidden" name="cmd" value="_s-xclick" />
<div id="partnerFormButton">
<br />
<asp:ImageButton runat="server" Name="btnSubmit" Text=" Next "
ID="btnSubmit"
ImageUrl="https://www.paypalobjects.com/en_GB/i/btn/btn_buynowCC_LG.gif"
onclick="btnSubmit_Click" CausesValidation="False" ></asp:ImageButton>
</div>
</div>
</form>
Code Behind code:
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
//some code
}
But the problem is that OnClick event doesn't firing and it redirects to the specified action url.
What can be the problem?
Thank you so much in advance...!!
It's not how ASP.NET events work. Events are fired after postback is made and you are preventing the postback by submitting the form. You need to decide what to do - either submit data with the form (like what you are doing now) and not use OnClick event or use the event and remove action and method parameters from form.
http://msdn.microsoft.com/en-us/library/ms178472.aspx
To explain it further: an event will not fire right after you click the button. What happens is that a POST request is being made to the same page with the page state passed in the ViewState. In other words - pressing the button in ASP.NET by default works kind of like a link to the same page (it's a veeeery simplified explanation though). Events are fired only after that request is made and after the page is loaded again - see the link above.
What you are doing right now is forcing the request to go to another page. Even though the button 'wants' to do a postback, the action parameter in your <form> points the request somewhere else. Since the postback isn't made and your page isn't loaded again, the event will not fire.
IISTe Technologies is going to introduce a blog for their student and other developers where they can find and share their problem and solution regarding c, c++, .NET java, PHP and others, here you one can find the exact solution of their programming problems.
Basically you have specified the action in the form tag.
You can redirect the page to "https://www.paypal.com/cgi-bin/webscr" in the click event. For if u specif action then you you wont be able to sumbit the data of the for. You won't get the values.
It will never go to the click event code block you have written. Because you are posting the page to paypal page instead of self.
Try this:
Remove action attribute from form.
Write click event as
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
var target = #"https://www.paypal.com/cgi-bin/webscr";
Response.Status = "307 Temporary Redirect";
Response.AddHeader("Location", target);
}

C# web application event handling

Which type of event would i place on a textbox to cause an action on the web form when the cursor leaves that textbox ?and how can i implement this?
I actually want to display a message on the form after details have been entered in the last textbox to notify users if they have left any field blank. I hope to apply this on the last textbox on the form.
I know an event handler shoud be able to instantiate this but am not sure which event would do this and how to implement it....
all advices are warmly welcome..
Thank you..
I think you are probably going to want to look at the ASP.NET validation controls. They should be able to handle what you are wanting to do.
http://devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=46
http://msdn.microsoft.com/en-us/library/aa479045.aspx
You'll need to use javascript on the client to handle this. What you want to do is add a handler for the blur event. The blur event occurs when an element loses focus. Use this in conjunction with your client-side validation logic to trigger validation when the field loses focus.
I prefer adding my javascript unobtrusively. Below is an example of how you would do it using jQuery and the jQuery validation plugin. Using it with standard ASP.NET validators would work as well, just replace the call to the validation logic with that for your client-side validators, i.e., call Page_ClientValidate().
<script type="text/javscript">
$('form').validate(); // set up validation
$('#lastTextBoxID').blur( function() {
$('form').valid(); // validate when the blur event happens
});
</script>
You can put the textbox inside a div and add ur function in the event of onmouseover()
like this :
<div onmouseover="ChangeFocus()">
<asp:TextBox runat="server" ID="TxtBox1"></asp:TextBox>
</div>
<script type="text/javascript" language="javascript">
function ChangeFocus()
{
var Details = document.getElementById('<%=TxtBox1.ClientID %').text;
//Display the details of the textbox in the place u need
}
</script>
And take care to adjust the width of the div and the textbox to fit it.
or u can replace asp textbox with input field of type "text" and set it's event onmouseover to the function ChangeFocus().
Hope that this will be usefull
You could do something like this:
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server"
ErrorMessage="The name field is required."
ControlToValidate="txtName" Display="None">
</asp:RequiredFieldValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
Could the TextChanged event be a likely solution? and when would this event occur?
I tried that but it didnt work... It appears that the event fires after the page has been validated (on button click).
any work arounds?

Categories