ASP OnText event based controlling button control - asp.net

What I'm trying to do is has a specific button enables or disables based on the number of characters that have been imputed into a textbox.
The event only fire when I click off the textbox, maybe i'm looking for something else?
<telerik:RadTextBox ID="InputVinInformationTextBox" runat="server"
Skin="Office2010Blue"
Width="250px"
MaxLength="16"
OnTextChanged="InputVinInformationTextBox_OnText"
AutoPostBack="true">
</telerik:RadTextBox>
protected void InputVinInformationTextBox_OnText(object sender, EventArgs e)
{
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}

If you don't mind using jQuery you could remove the OnTextChanged function and instead bind the functionality to the keyup event. All you need to do is to add the following in your <head> tag:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("#<%=InputVinInformationTextBox.ClientID%>").keyup(function() {
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}
});
</script>
I'm not sure what your VinSubmitButton is, but I assume, since it was working in your example, that that is an element that you already have stored.

This behavior is by design:
All RadInput controls provide the TextChanged server event, which is
raised when the AutoPostBack property is set to true, the user types
valid entry, and the input loses focus.
The TextChanged event only occurs if the value of the input control
actually changes. If the user changes the string in the input control
but does not actually change the value...the TextChanged event does
not occur.
See this help topic on Telerik's site for more info.
I recommend using the OnTextChanged event as you have been, as it will only fire when valid text is entered that changes the previous value of the RadTextBox.
Alternatively, you can use JavaScript to determine when an appropriateĀ number of characters have been entered, then trigger the request manually.
<telerik:RadTextBox ID="InputVinInformationTextBox" runat="server"
Skin="Office2010Blue"
Width="250px"
MaxLength="16"
OnLoad="InputVinInformationTextBox_OnLoad">
<ClientEvents OnKeyPress="InputVinInformationTextBox_OnKeyPress" />
</telerik:RadTextBox>
<script type="text/javascript">
function InputVinInformationTextBox_OnKeyPress(sender, args) {
var text = sender.get_value();
if (text.length >= 8) {
var ajaxManager = $find('<%= RadAjaxManager.GetCurrent(Page) %>');
ajaxManager.ajaxRequestWithTarget(sender.get_id(), '');
}
}
</script>
The code above assumes you are also using a RadAjaxManager on the page and that it has been configured to update all/part of the page when triggered by the RadTextBox. You'd need to check the RadTextBox value during the OnLoad event of the control (or later) so that all ViewState and form values have been initialized for the control.
protected void InputVinInformationTextBox_OnLoad(object sender, EventArgs e)
{
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}

Related

using AutoPostBack doesn't work when setting input value in JS

I have a custom control which inherits from TextBox.
This allows me to use the TextBox's AutoPostBack property. This property makes the Page_Load method on the parent page fire when I change the value and click out of the text box.
I am setting the value of the rendered text box in JS as follows
var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = barcode.Value;
When this code runs I am expecting the Page_Load method to run again.
I have tried things like
outputData.focus();
outputData.value = barcode.Value;
outputData.blur();
The code in the Page_Load is
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Label1.Text = CameraScannerTextbox1.Text;
}
}
So basically I am hoping to have whatever is in barcode.Value set on Label1.Text on the server.
All you need is to trigger onchange event for input since ASP.NET adds postback code to onchange attribute. The simplest way is calling onchange manually
var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = barcode.Value;
outputData.onchange();
For more advanced techniques of simulating onchange event see this and this answers.
You can simply trigger the PostBack yourself with __doPostBack.
<asp:TextBox ID="CameraScannerTextbox1" runat="server" ClientIDMode="Static" AutoPostBack="true"></asp:TextBox>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
<script>
var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = '123456';
__doPostBack('CameraScannerTextbox1', '');
</script>
</asp:PlaceHolder>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Label1.Text = CameraScannerTextbox1.Text;
PlaceHolder1.Visible = false;
}
}
Not that I placed the javascript in a PlaceHolder that is hiddedn on PostBack, otherwise it will create a PostBack loop. But there are other ways to prevent that also.

Avoid postback on button click

I have a Search feature. if the search string is empty and user clicks "GO" then the postback of the gridview shouldn't happen and the alert (as mentioned in below code) should get fired up.
My gridview is in update panel. Below is the logic that i have written but it doesn't works.
protected void btnGo_Click(object sender, EventArgs e)
{
if (!txtSearchString.Text.Equals(string.Empty))
{
BinGrid();
upnl1.update //update panel is updated here.
}
else
{
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Search", "alert('Enter search text');", false);
//upnlgvOpportinities.Update();
//upnlAdmin.Update();
return;
}
}
Please help! Let me know if any info is needed
This logic is wrong. It should do using javascript if you want to avoid the postback at first place.
Have your javascript return false when textbox is empty and true when not
<asp:button runat="server".... OnClientClick="return myfunction(); " />
You can check if textbox is empty or not in myfunction()
Replace Your ScriptManager line with below code line.
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Script", "alert('Enter search text');", true);
If you don't want a request to the server to be sent (if I understood your needs right), than you need a client-side solution, that is handle button click with javascript and conditionally prevent the postback. However your current code is server-side, and is executed on a server after the postback has occurred.
As to client-side, here is one possible way. Define a js function that simply checks the value of the search box and returns false if it is empty. On the button click simply call this function. If a click handler returns false, further processing of the button click will be stopped and the postback won't occur:
function checkSearch() {
var searchBox = document.getElementById('HereComesSearchBoxClientID');
if (searchBox.value == '') {
alert('Enter search text');
return false;
} else {
return true;
}
}
<asp:Button ID="SearchButton" runat="server" Text="GO" OnClick="ServerSideHandler" OnClientClick="checkSearch();" />
#Madhur Ahuja's way is the correct one. Expanding that a little bit more.
HTML
<asp:Button ID="txtSearchString" runat="server"
OnClientClick="javascript:return CheckifEmpty(this);" />
Javascript
function CheckifEmpty(objSearchBox) {
//always trim, otherwise it will accept a string of spaces
var isEmpty = objSearchBox.value.trim() == "";
if (isEmpty) {
alert('Enter search text');
}
return !isEmpty;
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}

window.location.href not working in Safari when using onkeypress

I'm using an asp textbox and a search button. In Safari if I click the search button i get redirected to the search results page using javascript window.location.href. But strangely the same javascript will not redirect to the page if I press return in the textbox.
Using the alert function I can see that window.location.href has the the correct url and the location bar at the top changes from the search page(default.aspx) to the search results url however when I click OK to the alert box the url at the top reverts back to the default.aspx page. It works on ie7/8/firefox/chrome but not safari. Here is my javascript,cs and aspx code:
function submitSearchOnEnter(e) {
var CodeForEnter = 13;
var codeEnteredByUser;
if (!e) var e = window.event;
if (e.keyCode) codeEnteredByUser = e.keyCode;
else if (e.which) codeEnteredByUser = e.which;
if (codeEnteredByUser == CodeForEnter)
RedirectToSearchPage();
}
function RedirectToSearchPage() {
var searchText = $get('<%=txtHeaderSearch.ClientID%>').value
if (searchText.length) {
window.location.href = "Search.aspx?searchString=" + searchText;
}
}
protected void Page_Load(object sender, EventArgs e)
{
txtHeaderSearch.Attributes.Add("onkeypress", "submitSearchOnEnter(event)");
}
<asp:Panel ID="pnlSearch" runat="server" DefaultButton="lnkSearch">
<asp:TextBox ID="txtHeaderSearch" runat="server" CssClass="searchBox"></asp:TextBox>
<asp:LinkButton ID="lnkSearch" OnClientClick="RedirectToSearchPage(); return false;"
CausesValidation="false" runat="server" CssClass="searchButton">
SEARCH
</asp:LinkButton>
</asp:Panel>
I've tried return false; which doesn't allow me to enter any characters in the search box. I've spent ages online trying to find a solution. Maybe it has something to do with setTimeout or setTimeInterval but it didn't work unless i did it wrong.
In Safari, the 'onkeypress' event is only fired if the key press results in a character being added to an HTML element. I'm not sure that this will fire at all when you press Enter in a one-line text box. See a partial explanation of this behavior here.
As Tim Down says, you probably want onkeydown instead.
Use keydown instead of keypress and you should be fine.
protected void Page_Load(object sender, EventArgs e)
{
txtHeaderSearch.Attributes.Add("onkeydown", "submitSearchOnEnter(event)");
}
I had a similar issue.
It worked for me when using onKeyUp:
function bodyOnKeyUp(event)
{
if (!event) {event=window.event;}
var Esc = 27;
switch (event.keyCode) {
case Esc:
document.location.href='URL';
break;
}
}
<body onKeyUp="bodyOnKeyUp(event)">
...
</body>

How to capture 'Update' click event in ASP.NET GridView with jQuery

I need to capture the 'Update' click event with jQuery in an asp.net GridView and have no way of knowing where to start. I'm still rather new to jQuery. My GridView is attached to a SQLDataSource and, naturally, has all the bells and whistles that that combination affords. Any help would be greatly appreciated.
Simply add the script block anywhere after the GridView is declared and it should work with the default non-templated GridView column. No code in the codebehind as it is purely a Javascript solution.
Use this if you are using a Link-type GridView column:
<script type="text/javascript">
// a:contains(The text of the link here)
$('#<%= theGridViewID.ClientID %> a:contains(Update)').click(function () {
alert('Update click event captured from the link!');
// return false: stop the postback from happening
// return true or don't return anything: continue with the postback
});
</script>
Use this if you are using a Button-type GridView column and you don't want your Javascript to block the postback:
<script type="text/javascript">
// :button[value=The text of the button here]
$('#<%= theGridViewID.ClientID %> :button[value=Update]').click(function () {
alert('Update click event captured from the button!');
});
</script>
Use this if you are using a Button-type GridView column and you want to have control whether to continue with the postback or not:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons
.attr('onclick', null)
.click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
var index = updateButtons.index($(this));
// 'Update$' refers to the GridView command name + dollar sign
__doPostBack('<%= theGridViewID.UniqueID %>', 'Update$' + index);
}
});
</script>
Update: I think this would be a better solution in replacement of the last (3rd) script block I presented above, since you won't need to update the __doPostBack function call manually based on the command name, and as such, it should be less error-prone:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons.each(function () {
var onclick = $(this).attr('onclick');
$(this).attr('onclick', null).click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
onclick();
}
});
});
</script>
Credit to Aristos for this idea. :)
Ok here is my solution to capture only one update (or more) from a button.
This is the javascript code that I run on update click
<script type="text/javascript">
function NowRunTheUpdate(){
alert("ok I capture you");
}
</script>
and here is the page code
`<asp:GridView ID="MyGridView" runat="server" OnRowDataBound="MyGridView_RowDataBound" ... >`
<asp:ButtonField Text="update" CommandName="Update" ButtonType="Button" />
...
Here is the code thats run behind and set the javascript.
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// I go to get the button if exist
Button button = control as Button;
if (button != null && button.CommandName == "Update")
// Add delete confirmation
button.OnClientClick = "NowRunTheUpdate();";
}
}
}
}
You need to attach a client-side event listener to the click event of the Update [link]button. I don't think it can be done using AutoGenerateEditButton="true" if you are doing it that way. You'll need to use a TemplateField so that you can manipulate the button. Then you can use jQuery to bind to the click event of the button.
Add the update column to the column templates. Convert it to a custom column, and modify it in such a way you can hook to it with jquery i.e. like adding a css class to it.
Gridview is nothing but a table with a bunch of "tr" and "td". If you understand that concept then it would be easy for you to handle anything at client side. If you have enabled auto everything then it will be a link which would result for Edit, Delete, Update or Cancel (Check View Source). The code given below should capture the update click event:
$("a:contains(Update)").live("click", function() {
//alert("hi"); do what needs to be done
return false;//would not sent the control back to server
});
HTH

Display confirmation box in ASP.NET using JavaScript

I need to show the confirm box "Are you sure You Want To continue?" If "Yes" I need the ASP.NET textbox value to be cleared out. Otherwise it should not be cleared.
function doConfirm(){
if (confirm("Are you sure you want to continue?")){
var mytxtbox = document.getElementById('<% =myAspTextBox.ClientID %>');
mytxtbox.value = '';
}
}
Note the myAspTextBox refers to the name of the asp:textbox controls ID property
<asp:textbox ID="myAspTextBox" runat="server" OnClientClick="javascript:doConfirm();"
Hope this helps
In your asp textbox tag add this:
OnClientClick="javascript:testDeleteValue();"
...
And add this script:
<script>
function testDeleteValue()
{
if (window.confirm('Are you sure You Want To continue?'))
document.getElementById("<%=<th id of your textbox>.ClientID%>").value = '';
}
</script>
If you want this to happen on click of your radio box, put it in this tag and just replace onclientclick with onclick.
<input type='radio' onclick='testDeleteValue()'/>
If you download the AjaxControlToolkit you can use the ConfirmButtonExtender to display a simple confirmation box to a user after a button is clicked to proceed with the action or cancel
You can see here for an example and here for a tutorial on how to implement this
Okay I just noticed the bit about radio buttons, in any case the AjaxControlToolkit is a good place to start if you want to implement JavaScript solutions in .Net projects
if this is your textbox markup:
<asp:textbox id="txtInput" runat="server" />
and then this is the button that will trigger the confirm:
<asp:button id="btnSumbit" runat="server" onclientclick="return clearOnConfirm();" text="Submit" />
then you'll need the following javascript:
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
return true;
} else {
return false;
}
}
</script>
If all you want to do is to clear the textbox but always continue with the postback then you don't ever need to return false as above but always return true as below. In this scenario you should rethink the message you display to the user.
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
}
return true;
}
</script>
function stopTimer() {
if (window.confirm('Are you sure You Want To continue?')) {
$find('Timer1')._stopTimer()
return true;
}
else {
return false;
}
<asp:Button ID="Btn_Finish" runat="server" Text="Finish" Width="113px" OnClick="Btn_Finish_Click" OnClientClick="return stopTimer();" Height="35px"
protected void Btn_Finish_Click(object sender, EventArgs e)
{
Timer1.Enabled = false;
// if any functions to be done eg: function1();
Response.Redirect("~/Default2.aspx");
}
There is also a timer stop doing in the function. The confirmation box if press "Ok" timer stops and also its redirected to new page "Default2.aspx"
else if chosen cancel then nothing happens.

Resources