Obtaining control Id through javascript in asp.net - c#

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
});

Related

Validating textbox only if checkbox is checked - no post back

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;
};

Prevent page being post back if javascript validations fails

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();"/>

Responding to an "enter" keypress within an <input> field

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
}
});

C# Disable/Enable Button based on Empty/Populated Text Boxes

I have a form with 5 text boxes and a button, and when the button is clicked it send the data to a SQL database. I would like the button to be disabled if any of the text boxes are null, how do I do this in C#? (I am in Visual Studio 2010 ASP.NET web app)
You need to write JavaScript/jQuery code.
Yes, What Sam said is right!!
you need to check first whether all your text boxes are empty or not.
that will be done by
If(txtbox1.text == "" || txtbox2.text == "" || txtbox3.text == "" || txtbox4.text == "" || txtbox5.text == "")
If any of the text box is empty then make the button disabled.
button1.enable = false;
If all are filled then make it as enabled.
button1.enable = true;
If you do not want to use Client side scripts, you can use validations for your controls
<asp:TextBox id="TextBox1" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="Required!" ControlToValidate="TextBox1" >
</asp:RequiredFieldValidator>
Validation will trigger on postbacks.
If you have multiple controls, but you do not want to validate them all, you can use Validation Group. Check this link for using Validation Groups
use javascript setInterval on Page load if if you are using this single form on the page and check each textbox value length .. if anyone is null then disable submit button..
use jquery to disable and enable them.. check following code snippet that i have created for sample..
use this to access server control id if you are using these controls inside some container control eg. panel, contentplaceholder etc : $("#<%=button1.ClientID>%>")
$("#text1").val().length will check then length of text in textbox.. and then use jquery to enable and disable them..
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>
<%-- <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js" type="text/javascript"></script>--%>
<%--<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7-vsdoc.js" type="text/javascript"></script>--%>
<script type="text/javascript">
$(document).ready(function () {
$("#submit").attr('disabled', 'disabled');
$("#text1").keypress(function () {
check();
});
var intv = self.setInterval("check()", 1000);
});
function check() {
if ($("#text1").val().length > 0) {
$("#submit").removeAttr('disabled');
}
else {
$("#submit").attr('disabled', 'disabled');
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="text1" runat="server"></asp:TextBox>
<asp:Button ID="submit" runat="server" Text="Button" />
</div>
</form>
</body>
</html>

Retrieve a TextBox using JavaScript

I have a GirdView in Edit Mode with inside a TextBox.
I need to Retrieve this TextBox with ID (from the source code in the browser) in JavaScript.
ctl00$MainContent$uxListOptions$ctl02$uxValueInput
But I receive an error because my JavaScript is not able to find the TextBox.
Here is the code:
<span onclick="encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')">
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="[Publish]" />
</span>
In my control’s OnPageLoad I call this:
private void addEditorJavaScript()
{
// create our HTML encoder javascript function
// this way it shows up once per page that the control is on
string scr = #"<script type='text/javascript'>function encodeMyHtml(name){
var content = document.getElementById(name).value
content = content.replace(/</g,'<');
content = content.replace(/>/g,'>');
document.getElementById(name).value = content;
}</script>";
// add the javascript into the Page
ClientScriptManager cm = Page.ClientScript;
cm.RegisterClientScriptBlock(this.GetType(), "GlobalJavascript", scr);
}
I am trying to use this code http://dustyreagan.com/how-to-submit-html-without-disabling/
Any Idea what am I doing wrong? Thanks guys!
If you are using ASP.Net 4.0, you could use ClientIdMode=Static or Predictable for this control.
encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')
This will result in
encodeMyHtml('ctl00_MainContent_uxListOptions_ctl02_uxValueInput_FormViewContentManager_ContentTextBox')
Does a control of that ID exist in your DOM?
It seems that you're making a lot of assumptions as to how the ID's will be created. It would be better to immediately reference the ContentTextBox.ClientID.
Something like the following, provided that ContentTextBox is a valid reference to the text box:
encodeMyHtml('<%# ContentTextBox.ClientID %>')
You can define your grid like this :
<div>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Calibri"
Font-Size = "12pt" HeaderStyle-BackColor = "LightYellow" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" CssClass="css1 mycss" Text='<%# Eval("Period")%>'
onblur="SetPostingPeriod(this)"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</div>
And your Javascript Function Would be :
<script language="javascript" type="text/javascript">
/* Populating same data to all the textboxes inside grid,
once change of text for one textbox - by using jquery
*/
function SetPostingPeriod(obj) {
var cntNbr = $("#" + obj.id).val();
// var cntNbr = document.getElementById(obj.id).value;
// alert(cntNbr);
//Access Grid element by using name selector
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
});
}
</script>
This Javascript function is called onblur event of the textbox.
When this function is called at the same time it passes a parameter
which is nothing but the textbox id.
Inside javascript function by using the parameter which is the
id of the textbox we are getting the vaue.
Here is the code :
var cntNbr = $("#" + obj.id).val();
Then For each of the "txtPeriod" controls available inside the grid, we need to assign
the value of current "txtPeriod" textbox value to them.
Looping Grid to identify each "txtPeriod" available :
Here is the code :
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
});
Inside this loop we need to assign the "txtPeriod"(current/Modified) value to other
"txtPeriod" textboxes.Before assign its good practice to check is it null or NAN.
Here is the code :
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}

Categories