I've a web page with a textbox as below -
<asp:TextBox ID="txtNumber" runat="server" size="5" MaxLength="9"
AutoPostBack="True" OnTextChanged="txtNumber_TextChanged"
CssClass="txtBoxPage" Style="margin-left: 3px;"
Visible="false" onblur="return [some JS function] false;">
</asp:TextBox>
I want a functionality such that if User enters Nothing i.e. ('') in textbox and move the cursor outside the textbox then Postback should not trigger. Currently it's getting triggered even after onblur event returns false.
If textbox value is empty, you can supress TextChanged event as below -
Add following line in Page_Load -
protected void Page_Load(object sender, EventArgs e)
{
txtNumber.Attributes.Add("onchange", "if(checkEmptyValue(this)) {return false; }");
}
Include following JavaScript in markup -
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
function checkEmptyValue(o) {
if (o.value == '' || o.value.trim() == '')
return true;
else
return false;
}
Try above code and let me know if it works.
document.getElementById('txtnumber').onchange=function(){
if(this.value!=""){
_doPostBack('txtNumber',this.value);
}
}
You can then retrieve the value by using the Request["__EVENTARGUMENT"] entry. Also, make sure to turn AutoPostback off.
EDIT: Within your txtNumber_TextChanged handler, for example:
private void txtNumber_TextChanged handler
{
Response.Write(Request["__EVENTARGUMENT"]);
//Writes the value of the TextBox. Basically, EVENTARGUMENT is the second argument passed when calling _doPostBack
}
Note that this is entirely optional, since you can still access the value of txtNumber using the txtNumber object (as is traditional).
EDIT: Note that when using document.getElementById to retrieve a reference to the element, you need to pass the client ID as the argument. If, for example the txtNumber object is within a FormView named FormView1, the resulting client ID will be FormView1_txtNumber. One of the following modifications to your code should fix the issue:
1) If your javascript is in a script tag on the aspx page, simply modify document.getElementById('txtNumber') to document.getElementById('<%= txtNumber.ClientID %>')
2) If you are using an external js file, change document.getElementById('txtNumber') to document.getElementById(txtNumberClientID) and insert the following script tag in your aspx page before you call your js file:
<script type="text/javascript">
window.txtNumberClientID='<%= txtNumber.ClientID %>';
</script>
Let me know if this works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With