My question is about handling Enter key press.I have one page called "order.aspx" which is residing inside master page.Here i am explaining the control structure
1. <asp:TextBox ID="txtSearch" MaxLength="50" runat="server" Width="420px" CssClass="txtbox"></asp:TextBox>
2. <asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" />
3. one asp grid control with one column containing textbox for entering order quantity
4. <asp:Button ID="btnOrder" runat="server" OnClick="btnOrder_Click" />.
My requirement is,
while user enter text in the search textbox and press enter key then btnSearch_Click should fire
while user enter quantity in the grid textbox and press enter key then btnOrder_Click should fire.
I tried with different code finally got answers but it is not fully functional.Follwing is the javascript code i have used.
function DoEnterKeyButtonClick(buttonId) {
e = event;
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
document.getElementById('ctl00_CphMaster_' + buttonId).click();
return false;
}
}
I am calling this method on key press of txtSearch and grid textbox and passing the Button id to fire event btnSearch and btnOrder respectively.When i am entering the text in the search textbox and hitting the enter key then btnSearch_Click is firing and when i am entering the order quantity and hitting the enter key the btnOrder_Click is firing.But the issue is,after changing the page index say second page the required functionality not working.That is when i am entering order quantity and hitting the enter key then btnSearch_Click will fire first , then btnOrder_Click firing.This will clear the quantity entered and results in error.Please help me...
Thanks,
Joby
Instead of giving this document.getElementById('ctl00_CphMaster_' + btnSearch).click();
Try this document.getElementById('<%= btnSearch.ClientID %>').click();
or try using jquery
$("#txtSearch").keyup(function(event){
if(event.keyCode == 13){
$("#btnSearch").click();
}
});
Else place your controls inside the asp:panel and set the DefaultButton property as btnSearch as like below
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSearch">
<asp:TextBox ID="txtSearch" MaxLength="50" runat="server" Width="420px" CssClass="txtbox"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" />
</asp:Panel>
Hope this will help.
Many Thanks
Anna
Your function doesn't know what exactly this even is.
Try it like this
function DoEnterKeyButtonClick(event,buttonId){}
I keep the following handy snippet around..
function getIntKey(key) {
var keycode;
if (key == null) { keycode = event.keyCode; } else { keycode = key.keyCode; }
return keycode;
}
And use it, like this..
$("#txtSearch").keyup(function(e){
if(getIntKey(e) == 13){
//Enter was pressed, do somthing
}
});
Related
I have a asp.net CheckBox and I have a textbox, I only want textbox to validate when checkbox is checked otherwise just leave it like this.
I find MVC post but I want for asp.net forms Validating textbox only if checkbox is checked using MVC
This is my current code which validates textbox regardless of checkbox is checked or not,
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject" ErrorMessage="You must enter a subject." runat="server" />
You will need a custom validator ,then:
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CustomValidator ControlToValidate="txtSubject" OnServerValidate="IsTextboxValid" Text="Text box is invalid" runat="server"/>
In code behind,define custom validation method:
protected void IsTextboxValid(object sender,ServerValidateEventArgs e)
{
e.IsValid=chkSubjectRequired.Checked;
}
Please note that this is Server-side Validation
this is what you looking for. Just enable/disable the validator (also textbox if you want) that's all.
Validate The Text Box Only Number :
<input type="text" onkeydown="ValidateNumber(event);">
<script>
function ValidateNumber(e) {
if ((e.keyCode >= 8 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
return true
}
return false;
};
I have a scenario in my asp.net application where when enter button is keyed in any of the multiline textboxs, I need to add a particular length to the existing length and show it in another control. I have written a generic javascript function to handle key-in in "pnlEnglish" panel. I can find out "Enter key" key up by checking "e.keycode ==13" , However would it be possible to know from which control I am firing the event??. I am trying to avoid adding events to text box since, I have to handle it for too many. Is there any better solution to achieve this??
<asp:Panel ID="pnlEnglish" runat="server">
<asp:TextBox ID="txtPlot" runat="server" Rows="5" TextMode="MultiLine" Width="350px" TabIndex="12"></asp:TextBox>
<asp:TextBox ID="txtLegacyPlot" runat="server" Rows="5" TextMode="MultiLine" Width="350px"TabIndex="12"></asp:TextBox>
</asp:Panel>
Javascript is as below
$('#<%=pnlEnglish.ClientID%> input:text,#<%=pnlEnglish.ClientID%> textarea').keyup(function (e) {
if (e.keyCode == 13) {
//Need to identify the control for which I shall add the length
}
var txtLenPlot = $('#<%=txtPlot.ClientID%>').val().length;
var txtLenLegacyPlot = $('#<%=txtLegacyPlot.ClientID%>').val().length;
//The below function shows the length in length displaying control
update_chars_left(500, $('#<%=txtLengthPlot.ClientID %>'), txtLenPlot);
update_chars_left(205, $('#<%=txtLengthLegacyPlot.ClientID %>'), txtLenLegacyPlot);
});
In side key up function you can get id of textbox in which enter key is pressed as below
$('#<%=pnlEnglish.ClientID%> input:text,#<%=pnlEnglish.ClientID%> textarea').keyup(function (e) {
if (e.keyCode == 13) {
var currTextboxId = $(this).attr('id');
//Your Code
});
In my asp.net application (v4.0), I have a grid view. I use a list object to bind data to the grid view.
In the grid view there is a cancel button. On click of the cancel button the application should pop a message to the user asking for confirmation to proceed with cancel. ie. are you sure you want to cancel the record yes/no. When the user selects yes then the particular record should be cancelled.
Now the issue is, when the user selects yes then i need to the get the index of the row for which the cancel button is clicked and i need to remove it from the list object that is used to bind the grid and rebind the gridview .
please let me know how to achieve this.
Thanks for all the reply.. im using custom pop up instead of built in 'confirm' method. The custom pop up will have 'OK' and 'Cancel' button controls. Only on click of 'OK' button i need to get the selected record index. Built in confirm method mentioned in some replies will not suit my scenario. please let me know how to achieve this.
Add a hiddenfield into your page
<asp:HiddenField ID="HiddenField1" runat="server" />
Use the Id(use corresponding column name instead of Id) of the records as the CommandArgument of Cancel button
<asp:Button ID="btncancel" runat="server" CommandArgument='<%#Eval("Id") %>' Text="Cancel" />
Then on clicking the cancel button it calls the gridviews rowcommand function. In that function keep the CommandArgument value in the hidden field as follows
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
HiddenField1.Value = e.CommandArgument.ToString();
}
Then on clicking the OK button, it calls the click event. In that function remove the Item from the List and then bind the list again to the gridview
protected void btnOK_Click(object sender, ButtonClickEventArgs e)
{
string id = HiddenField1.Value;
//use this id to remove the data from the List
// bind the gridview
}
Try this..
You can use javascript function..
<asp:Button ID="Button1" runat="server" onclientclick="Validate(this) />
Declare an HTML hidden field in your page...
<input id="Hidden1" type="hidden" runat="server" clientidmode="static"/>
function Validate(obj) {
var r = confirm("are you sure you want to cancel ?");
if (r == true) {
var id = obj.id.toString();
var index = id.split("_");
var RowNumber = index[2].toString();
document.getElementById('Hidden1').value=RowNumber ;
}
else {
return;
}
}
Here we get id of the button somewhat as ContentPlacedholde_Button1_0..Then we split it to get the index..
Use command name and command argument on cancel button like this:
<asp:Button ID="btncancel" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="Cancel" Text="Cancel" />
And then on gridviewRowcommand use this:
if (e.CommandName == "Cancel")
{
int count = GridViewName.Rows.Count;
for (int i = 0; i < count; i++)
{
int id = Convert.ToInt32(e.CommandArgument);
}
}
Have you tried adding a CommandArgument value to the cancel button that represents the item, for example an ID? Then onclick, display a popup, if the user selects yes then use the ID to remove the item from your collection, then simply rebind the grid. The item will then be gone.
I've following asp text box:
<asp:TextBox ID="txtPasswrod" runat="server"></asp:TextBox>
below this text box I've error message label, which is initially hidden until the js validation of the text box fails:
<label id="errorMsg" for="pwd" style="display:none">error</label >
Following is the js for textbox validation:
function validation()
{
var pwd = document.getElementById("txtPasswrod").value;
if (pwd == null || pwd == "")
{
document.getElementById("error").style.display = 'block';
return false;
}
}
Following is the asp button, whose OnClientClick event I am calling validation() function:
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" OnClientClick="validation()"/>
The validation is working all fine, but the problem is that when text box is empty and my validation fails the js should prevent page from being post back, but the js allowing the page being post back and my validation jst becoming useless.
Please tell me how to prevent page postback on failing the js validation.
Modify validation() to return validation(), This will stop page to post if function returns false.
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" OnClientClick="return validation();"/>
You need a slight change in your JS script. You need to add .ClientID as the control you are specifying is a server control. Or if you are on .net 4.0 , you can use ClientIDMode= "Static" to access the control as you are using in your code.
function validation() {
var pwd = document.getElementById('<%=txtPasswrod.ClientID').value;
if (pwd == null || pwd == "")
{
document.getElementById("errorMsg").style.display = 'block';
return false;
}
}
Now call the validation method something like this:
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" OnClientClick="return validation();"/>
I have a requirement where i have to update a textbox if any of the value in my grid view changes.. I have a gridview with 2 rows ..
one a template field with label and another template field with a textbox...
my Grid view looks like
name value
a (empty textbox)
b (empty textbox)
c (empty textbox)
now when the user enters a value in teh text box it should automatically update another textbox which is linked to this.
Here my questions is when someone enters a value in the textbox an event should be fired!
(I am getting the names a,b,c, from database). i dont want to have an edit link or update link because all the values to be entered are mandatory!
i tried Grid_SelectedIndexChanged1 but this not firing.. is there something i am missing or i need to change so that the evant is fired and i can update the other textbox??
I am new to ASP.NET so please help!
Thanks in advance!
If the updates are supposed to be triggered when the text changes, you should use the OnTextChanged event of the TextBox, and set AutoPostBack to true.
EDIT
To avoid duplicating efforts here, using the above approach you can find the row index using the technique that Pankaj Garg outlined in his answer:
int rowIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex;
The biggest caveat to this approach is that it's not forgiving of changes in the markup. If you were to wrap the TextBox in another control that implements INamingContainer, the example above would break. For example:
<asp:TemplateField>
<asp:Panel ID="Panel1" runat="server"> <!-- becomes the naming container -->
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:Panel>
</asp:TemplateField>
That being said, you would want to notate your markup accordingly so other developers know to be careful when making changes.
EDIT
As an alternative, you could also trigger the postback in JavaScript using the onchange event of the TextBox:
<script type="text/javascript">
valueChanged = function(rowIndex){
__doPostBack("<%= GridView1.ClientID %>", rowIndex);
}
</script>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" ...>
<Columns>
<asp:TemplateField>
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code-behind, override the RaisePostBackEvent method, and put your update logic there:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
if (source == GridView1)
{
int rowIndex = int.Parse(eventArgument);
TextBox txt = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox;
if (txt != null)
{
var id = (int)GridView1.DataKeys[rowIndex]["ID"];
var text = txt.Text.Trim();
//update the database
}
}
}
You can check the Current Row Index like below...
((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
Create a handler for OnTextChanged event and set the AutoPostBack Property True.
protected void TextBox_TextChanged(object sender, EventArgs e)
{
int CurrentGridIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
}