aspx change focus from different TextBoxes on the fly - c#

I am trying to change the focus from one textbox to another while the character count in
on textbox reaches 13 I am using the code below with nothing happening whatsoever:
if (!this.ClientScript.IsClientScriptBlockRegistered("qtyFocus"))
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "qtyFocus",
#"<script type='text/javascript' language='javascript'>function qtyFocus(){
var trckNumberLength = document.getElementById('txtTrackingNumber').value.length;
if(trckNumberLength == 13){
document.getElementById('txtQuantity').focus();
}}</script>");
}
txtTrackingNumber.Attributes.Add("onchange", "javascript:return qtyFocus();");
can anyone help please ?

Probably because the line in the script that's doing
var trckNumberLength = document.getElementById('txtTrackingNumber').value.length;
Needs to be changed for:
var trckNumberLength = document.getElementById('"+txtTrackingNumber.ClientID+"').value.length;
The reason being that txtTrackingNumber will very likely have a different Id when it's rendered on the page so you need to use the ClientID property of the control instead of the id you defined on the markup.

Related

Hidden field value updated but not showing updated value in codebehind?

I am setting the hidden filed value through JavaScript as below
<script lang="JavaScript" type="text/javascript">
function ChangeVal()
{
var elem = document.getElementById("btnDownloadStream");
if (elem.value == "Start")
{
elem.value = "Stop";
document.getElementById('myHiddenInput').value = "1";
}
else
{
document.getElementById('myHiddenInput').value = "0";
elem.value = "Start";
}
}
I am trying to get hidden field value in code behind. My code is
HiddenField myHiddenInput = (HiddenField)Page.FindControl("myHiddenInput");
var val = myHiddenInput.Value;
Before this line I am calling one function which creates and generates the GetResponseStream(). While doing this I am not able to get the value from server controls. Why?
Becuase Changing the value in javascript will not affect the server side value.
if you want to change a server side value from javascript: You can try the following
// Javascript
var myHidden = document.getElementById("<%:myHiddenId.ClientId%>");
myHidden.value = myJSVariable;
Make sure the myHidden is a server control.
Set Runat="server" attribute to your hidden field as shown below :
<input type="hidden" value="" id="myHiddenInput" runat="server" />
Then update your javascript function as shown below :
function ChangeVal() {
var elem = document.getElementById("btnDownloadStream");
if (elem.value == "Start") {
elem.value = "Stop";
document.getElementById('<%=myHiddenInput.ClientID%>').value = "1";
}
else {
document.getElementById('<%=myHiddenInput.ClientID%>').value = "0";
elem.value = "Start";
}
}
now you can directly access your hidden field value in your code behind without using Page.FindControl as mentioned :
var val = this.myHiddenInput.Value;
Update:
One thing I have noticed that your button is server side button and in your javascript you call
var elem = document.getElementById("btnDownloadStream");
I think it should be
var elem = document.getElementById('<%=btnDownloadStream.ClientId%>')
otherwise you will always get the value of else part
Make sure this is not the case.
well #Vishweshwar Kapse is answered your question.
Place your hidden field in update panel and don't forget to add click event of button in trigger.
This also happens in case you use the UpdatePannel in your page. if this is the case then place the HiddenField inside the UpdatePannel and try again.
You forget about ViewState. If you change data in the hidden field using java script code the ViewState do not get this changes and that's why you cannot get the correct value in code behind.
Make sure your hidden field have runat="server" attribute..

How to add class for only the selected link in C# code behind?

I have a class called "is-active" and it has a colored arrow that sticks out from the nav into the main content based on which link the user clicked. The code runs a foreach and pulls all the categories from the database. How do I get the "is-active" class to display only for the current link? I know it works since I put it in the openList control and it displayed on all five categories, I just don't know how to get it to display on only the selected category.
I tried attaching jQuery to do it but adding the linkbutton is done all in the code behind so I am not sure how to attach the two. Is this the only way or is there another way?
Thank you in advance for your help!
Below is my code for the categories and link button:
protected override void CreateChildControls()
{
LiteralControl openingDiv = new LiteralControl("<div id='MainPanel'>");
LiteralControl closingDiv = new LiteralControl("</div>");
this.Controls.Add(openingDiv);
foreach (DataRow dr in ds.Tables[0].Rows)
{
LiteralControl openList = new LiteralControl("<li class='" + dr["CategoryColor"].ToString() + "'>");
LiteralControl closeList = new LiteralControl("</li>");
Label lblNumber = new Label();
LinkButton myLinkButton = new LinkButton();
myLinkButton.Text = "<span class='number'>" + dr["CategoryNumber"] + "</span>"+ dr["CategoryName"].ToString();
myLinkButton.CommandArgument = dr["Category_ID"].ToString();
myLinkButton.Click += myLinkButton_Click;
this.Controls.Add(openList);
this.Controls.Add(myLinkButton);
this.Controls.Add(closeList);
}
this.Controls.Add(closingDiv);
}
void myLinkButton_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
Session["CategoryID"] = btn.CommandArgument;
Response.Redirect(Request.RawUrl);
}
Its tricky because your response.redirecting in the button click handler which recreates the pages viewstate.
This means that your page will always appear as fresh and the fact a user has clicked that link has been lost.
as a workaround you could place the link id in a session variable before you response.redirect and then recall it when the page reloads.
then when in your loop, if the session variable matches the current button instance.id you set cssclass equal to is-active.
remember to clear the session variable too after you set the cssclass to is-active to avoid confusion in other pages.
also, you will have to do the id comparison after you add the button to the control tree, because this is where the system automatically generates the id for you. I can give you a full example if you wish.
keep in mind that this is a workaround and a different approach would be best.
by this I mean that if you were to use an ispostback wrapper instead of a redirect, then on postback you could set the id to isactive much easier.
Page lifecycle is an important thing to get your head around in .net if you wish to be more proficient, especially as you mention that your using ajax update panels.
Read this: http://msdn.microsoft.com/en-us/library/ms178472(VS.100).aspx it's a lot of information to take in, so bookmark it for later too as you will use it a lot.

How to Check if ListBox is Empty on Client-Side

I created a javascript confirm as below.
<script Type="Text/Javascript">
function CheckListBox(lvi)
{
if(lvi == "")
{
if(confirm("Are you sure?"))
{
return true;
}
else
{
return false;
}
}
}
</script>
I need to test if the ListBox.Items control is empty... I already made reference on my aspx page
<script language="javascript" type="text/javascript" src="/JS/confirm.js"></script>
I want to know how to call it on my aspx.cs page . . . So I can pass the parameter:
string oi = Listbox_Clubes.Items.Count.ToString();//Its the parameter I want to pass
See this link for how to execute javascript from code behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "CheckListBox(" + Listbox_Clubes.Items.Count.ToString() + ");", false);
}
Note: you must add a ScriptManager control in aspx page.
For your javascript, you can get the value without the code-behind (this assumes the script code is in the same page, in order to get the client ID):
<script>
function ClickListBox() {
if ($("#<%= Listbox_Clubes.ClientID %>").val() === null) {
if (confirm("Are you sure?")) {
return true;
}
else {
return false;
}
}
}
</script>
Similarly, you don't use javascript to validate on the server side. The code you posted will return all items in the ListBox. Here is one way to get the count of the number of selected items (I'm using .ToString() based on the OP code example):
string oi = Listbox_Clubes.Items.Cast<ListItem>().Where(i => i.Selected).Count().ToString();
However, there is no reason why you would get this value and pass it back to the client-side to do validation (what it sounds like you want to do in your post). Mainly because this involves a post-back, and client-side validation, by its nature, should occur before post-back. Also, you will still need to do server-side validation, even when you have client-side validation.
Related: in the code-behind, you can test to see if anything is selected by:
bool hasValue = Listbox_Clubes.SelectedItem != null;
The .SelectedItem returns the selected item with the lowest index in the list control. When nothing is selected, this value is null... so you know if the value isn't null, then at least one item was selected.
If you want to require that they choose at least one item, you can use a RequireFieldValidator and let that handle both validations. If you haven't done much with ASP.NET validators, that would be one good thing to read up on.
It sounds like you probably should read more about client-side validation and server-side validation and how to use them... because it seems like you are mixing them up.
The count code is a modified version of code in ASP:ListBox Get Selected Items - One Liner?

Textbox onchange event

So I have a text box, where I add an onchange event of markAsException.
My javascript is -
function markAsException(recordID) {
//alert("Exception");
//mark exception column
document.getElementById("ctl00_cpMain_lblScrollException_" + recordID).innerText = "Exception";
document.getElementById("ctl00_cpMain_lblScrollException_" + recordID).style.color = "#FF0000";
document.getElementById("ctl00_cpMain_tdScrollException_" + recordID).style.backgroundColor = "#99CCFF";
//enable comments ddl and remove blank (first item)
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).disabled = false;
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).focus();
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).options[0] = null;
}
What I want to do is, when a user changes the value in a textbox, to mark a column as "Exception", and then focus a drop down list where they have to chose the reason for the exception.
This is what happens.. If I am on that text box and change it, then tab, it tabs to the drop down list.
However, if I change the value and then simply click in another text box on the form, I don't focus the drop down list.
How would I accomplish that?
I would suggest using JQuery's change() function.
The advantage is that it will be more stable across different browsers.
Something like:
$('#<%= TextBox1.ClientID %>').change(function(){
// extract the recordID from the textbox - perhaps with an attribute?
markAsException(recordID);
});
My comment was getting longer so I'm expanding:
Take a look at the JQuery documentation for setting this up as the page finishes loading. If tb is the ID of your textbox your selector would be
$('#<%= tb.ClientID %>')
I would suggest you replace your code and use
tb.Attributes.Add("recordID", recordId.ToString());
This will add the ID you need onto the textbox tag. Once you're in the function I outlined above you can use the following selector to get the recordID in javascript
var recordID = $('#<%= TextBox1.ClientID %>').attr('recordID');
All together
$(document.ready(function(){
$('#<%= tb.ClientID %>').change(function(){
var recordID = $('#<%= tb.ClientID %>').attr('recordID');
if(recordID){
markAsException(recordID);
}
});
});

copy several textboxes data into target textbox calling same function

I have several input textboxes with different id and class name. I want to track changes in any of the input textboxes, and reflect it into target textbox, but don't want to replicate the function for every individual textbox. Is it possible to use one function for all?
Appreciate your help
You can bind the change event for all the textboxes in the page using
$("input:text").change(function(){
var textValue = this.value;
$("#targetbox").val(textValue);
});
If the textboxes are inside a particular container then you can limit the search inside the container
$("#parentcontainer input:text").change(function(){
var textValue = this.value;
$("#targetbox").val(textValue);
});
try something like this..........
var finalValue ='';
$('.textBoxesId').each(function(){
$(this).change(function(){
finalValue = $(this).val();
});
});
$('#targetID').val(finalValue );

Categories