Enable asp button only when there is text in the asp textbox - javascript

Ok, so I have a multiple ASP textboxes and ASP buttons on a page within a multiview.
The submit button associated with each textbox should be enabled only when there is text entered in the textbox. So, I wrote a Javascript function to handle this and I'm getting an error saying "document.getElementById(...)' is null or not an object"
function checkEmptyTxtBox(val, savebtn) {
if (val.value.replace(/^\s+|\s+$/g, "") == "")
document.getElementById(savebtn).disabled = true;
else
document.getElementById(savebtn).disabled = false;
}
<asp:TextBox
ID="txt_Comments_2"
runat="server"
Wrap="true"
TextMode="MultiLine"
onkeyup="checkEmptyTxtBox(this,'<%= btnSave2.ClientID %>')">
</asp:TextBox>
<asp:Button
ID="btnSave2"
runat="server"
text="Save"
Enabled="False"/>
This is on VS2010.

You cannot set an attribute of a Server Side Control using <%= %>. If you look at the rendered source, it looks like this:
onkeyup="checkEmptyTxtBox(this,'<%= btnSave2.ClientID %>')"
It literally contains the <%= %>.
You could set the attribute on page load like this:
protected void Page_Load(object sender, EventArgs e)
{
txt_Comments_2.Attributes["onkeyup"] = "checkEmptyTxtBox(this,'" + btnSave2.ClientID + "')";
}
EDIT:
As many will be willing to point out; this isn't really the "best" way to do event registration in HTML. Rather, the JavaScript should bind to the keyup event by adding an event listener. For example, with jQuery it becomes:
$(document).ready(function() {
$('#<%: txt_Comments_2.ClientID %>').keyup(function() {
if ($(this).val().replace( /^\s+|\s+$/g , "") == "") {
$('#<%: btnSave2.ClientID %>').attr('disabled', 'disabled');
}
else {
$('#<%: btnSave2.ClientID %>').removeAttr('disabled');
}
});
});
And your ASP.NET markup looks like this:
<asp:TextBox
ID="txt_Comments_2"
runat="server"
Wrap="true"
TextMode="MultiLine" />
<asp:Button
ID="btnSave2"
runat="server"
text="Save"
Enabled="False"/>
This has the advantage of not cluttering your HTML with event registration. There are even other, perhaps cleaner ways of doing this with something like KnockoutJS.

This might be because the ID of your button is btnSave2 but you're passing <%= btnSave2.ClientID %> as the savebtn. Javascript cannot find the element by the id which you specified.
Also, I just read up on people who have had a similar issue and theirs was that they did not do a RegisterStartupscript.
Please check these out:
http://forums.asp.net/t/1160208.aspx/2/10?document+getelementbyid+is+null+or+not+an+object
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Related

How do I call a C# method using JavaScript in .NET Framework 4.7.2?

Whenever the textbox value changes a C# method should be called. The textbox uses a calendar validator so when a user changes the date it should count as a value change. The date can be changed by clicking on a new date or typing it in. Typing it in can possibly call the method multiple times which is fine. How can I activate a C# method whenever a textbox value is changed using JavaScript in .NET Framework 4.7.2?
.ascx file:
<script type="text/javascript">
$(document).ready(function () {
$("#textBox1).change(function () {
// How can I call the buttonClick method?
}
});
</script>
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="date" runat="server" ControlToValidate="textBox1"
ErrorMessage="Date Required" CssClass="field-validation-error"></asp:RequiredFieldValidator>
<ajax:CalendarExtender ID="ceDate" runat="server" TargetControlID="textBox1" />
.ascx.cs file:
protected void buttonClick(object sender, EventArgs e)
{
//...
}
I tried doing this without JavaScript. There is an OnTextChanged event listener that should call the buttonClick method. This has not been working for me. Clicking on a new date or typing in the textbox doesn't trigger the method. It only seems to trigger when I press the 'Enter' key. The event listener should not depend on the 'Enter' key being pressed.
.ascx file:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick"></asp:TextBox>
<asp:RequiredFieldValidator ID="date" runat="server" ControlToValidate="textBox1"
ErrorMessage="Required" CssClass="field-validation-error"></asp:RequiredFieldValidator>
<ajax:CalendarExtender ID="ceDate" runat="server" TargetControlID="textBox1" />
Method 1:
<script type="text/javascript">
$(document).ready(function () {
$("#textBox1").change(function () {
<%= Page.ClientScript.GetPostBackEventReference(textBox1, "") %>
}
});
</script>
But take care that under certain circumstances, the id value of the text box control will not necessarily be the same as the ID (name) of the textbox control on the server side. One way to make sure that your jQuery selector uses the correct value for the id of the textbox control is to use the ClientID property of the server-side object, like so:
<script type="text/javascript">
$(document).ready(function () {
$("#<%= textBox1.ClientID %>").change(function () {
<%= Page.ClientScript.GetPostBackEventReference(textBox1, "") %>
}
});
</script>
Or if you don't want to bother with using the ClientID property, then you can set the value of ClientIDMode attribute on the mark-up of the control to Static, then the id on the server and client will always be the same, like so:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick" ClientIDMode="Static"></asp:TextBox>
However, it is not advisable to use ClientIDMode="Static" within custom user controls, since you could end up with multiple elements with the same ID on the client when the control is used multiple times on the same page.
Method 2:
It is also possible to achieve all this without using JavaScript.
The buttonClick server-side event handler will not be called until the form is posted back to the server-side.
One way to automatically do a post-back to the server whenever the text is changed is by adding the AutoPostBack="true" attribute to the mark-up of the textBox1 control:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick" AutoPostBack="true"></asp:TextBox>
Side-note: Remember, doing a post-back will cause the whole page/control life-cycle to be executed, even if your controls are within an <asp:UpdatePanel>...</asp:UpdatePanel> block (for asynchronous/ajax updates), so things like the Page_Load function will be run every time there is a post-back. If you have initialization code within such functions and you don't want to re-initialize on every post-back, just check that the Request is not post-back before running initialization code, i.e:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// initialization
}
}

Server tag not well formed for ASP DropDownList for ItemTemplate

<asp:TemplateField HeaderText="Company Membership">
<ItemTemplate>
<asp:DropDownList id="ddlCompanyMembership" runat="server" class="form-control" onchange="verifyUser('<%# ((DataRowView)Container.DataItem)["CCMP_CODE"].ToString() %>');" />
</ItemTemplate>
</asp:TemplateField>
I can't seem to build this properly. It's suppose to call a Javascript function and pass the value to the function. But it shows Server tag not well formed error.
I've tried looking for solutions, some said the quotes and double quotes do matter. But I've tried everything and nothing's working.
You may consider binding onchange event on the server side by handling GridView's RowDataBound event. You will be able to bind your event as follows which is more convenient in my opinion.
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find your drop down list
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlCompanyMembership");
// Add onchange event as attribute
ddl.Attributes["onchange"] = "verifyUser('your logic');";
}
}
onchange="verifyUser('<%# DataBinder.Eval(Container.DataItem, "CCMP_CODE").ToString()%>');"
above code helps you to make it working.

how to call a written function in .aspx page from code behind

i have an asp:DropDownList and i want to disable it in some condition.it can happen with a function in aspx page.but from code behind (after some c# work) it wont!
this is the element:
ASPX:
<asp:DropDownList ClientIDMode="Static" ID="cmbState" runat="server" Width="130px" Height="30px" Font-Size="Small" Font-Bold="true" DataValueField="StateID" DataTextField="Name" AutoPostBack="True"></asp:DropDownList>
Code-Behind:
bool condition = true;
if (condition == true)
{
cmbState.Enabled = false;
}
This should work unless you have something in your Page_Load method which would counter it.
The AutoPostBack property is important due to the order in which events are carried out on the page.

Unable to read hidden field value from server side

I have a aspx page (default.aspx), inside which I am loading a user control (tree.ascx).
inside the tree.ascx there is a hidden field.
<asp:HiddenField ID="HiddenField1" runat="server"/>
I am assigning a value to the hidden field using javascript.
document.getElementById('<%=HiddenField1.ClientID%>').value = "some text here";
alert(document.getElementById('<%=HiddenField1.ClientID%>').value);
document.getElementById('form1').submit();
The alert displays the value absolutely fine. which means the value gets inserted in the hidden field properly.
But when I am posting back to server and checking the value, it is always null.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// do something.
}
else
{
string str = this.HiddenField1.Value;
}
}
My code is always getting a empty string here. somehow the postback is erasing the value from the hidden field.
What could be the reason?
Try using below syntax. It works for me even after postback.
ASPX code
<asp:HiddenField runat="server" ID="aspHiddenField" />
<input type="hidden" id="inputHidden" value='<%= aspHiddenField.ClientID %>' />
JavaScript Code
var inputHidden = document.getElementById('inputHidden');
$("#" + inputHidden.value).val("some text");
Code Behind
if (!string.IsNullOrEmpty(aspHiddenField.Value))
{
//Your code goes here
}
Check if your control is within a master page, if it is, then you need to access it like that, 1st Master Page->within master page look for the control's value, it will work surely.
Place your hidden field in update panel like :
<asp:UpdatePanel ID="UpnlHidden" runat="server">
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
This will work for you :-)

ASP.Net session not updated in javascript

when my button is clicked I fire the javascript to get the session..
But value of session not updated...
alert('<%= Session["file"]%>');
It won't be up to date if its changed after the page is rendered.
You might want to look at page methods (an ajax system) or another ajax approach.
Any inline code once rendered to the page will not change, which is a normal behavior.
use a Hidden field instead.
mark-up:
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
Session["file"] = "Data Here";
HiddenField1.Value = Session["file"].ToString();
}
javascript:
alert(document.getElementById('<%= HiddenField1.ClientID %>').value);

Categories