JavaScript for GridView row TemplateFields - c#

I'm creating a program where, in each GridView row, there is a checkbox and a textbox, which are unchecked and disabled by default respectively. When the checkbox is ticked, I need to fire a bit of JavaScript to enable that textbox, and vice versa for when is unticked. So far I am doing this:
JS:
<script type="text/javascript">
function onholdev(index) {
var chk = document.getElementById('<%=grdCons.Rows[index].FindControl("chkHold").ClientID %>');
var txt = document.getElementById('<%=grdCons.Rows[index].FindControl("txtReason").ClientID %>');
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
C# (RowDataBound event)
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev(" + e.Row.RowIndex + ")");
But in the JS, it's saying the 'index' variable does not exist, in the first line of the function (that begins with var chk). Am I doing this right?

the problem is that index is inside the string while it should be a parameter, this fixes it :
var chk = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("chkHold").ClientID %>');
the same goes for the other line

Since the check box will render as input we can able to find it by using the $('.check input') and since it is added dynamically we need to use jquery bind to add the click function to the check box.So in this I am getting the checked control by chk = $('.check input');.Each time when user checks a check box the function calls .I am here setting the visibility to none of all text box and when the user click it will find the next control and removing the class .hde using $(this).parent().next().removeClass('hide');.So the textbox will be visible next to the checkbox.
In your case I think by default you will make textbox disabled=false
.hide is used to set visiblity false.you can do disabling by adding attribute disabled to the textbox
css
.hide
{
display: none;
}
Designer Code
<ItemTemplate>
<asp:CheckBox ID="cbEnergyItems" runat="server" CssClass="check" />
<input type="text" id="txtQty" style="width: 25px" class="hide"
value="0" runat="server" />
<%# Eval("something") %>
</ItemTemplate>
Jquery
$('.check input').bind("click", function() {
var chk = $('.check input');
if ($(this).attr('checked')) {
//$(this).parent().next().removeClass('hide'); //removing the class to visible. you can do removing the attribute
$(this).parent().next().removeAttr("disabled");
if ($(this).parent().next().val() == ""0"")
showStatus(true, "Please enter the quantity");
}
else {
$(this).parent().next("disabled","disabled").
// $(this).parent().next().addClass('hide');
}
});
I think this will solve your problem.

Thanks all for your help, I sort of 'solved' it by not doing it serverside instead. Bit lazy but saves a lot of JS headaches.

Related

Pass C# variable through URL

I have defined a variable in C# as the item selected in a drop down.
string parametername = ddlCarrier.SelectedItem.Text;
I now want to pass this variable in my URL to the next page. How do I do this in the href tag?
<asp:LinkButton href="Table.aspx?parameter=<%parametername%>" ID="btnSubmit" runat="server">Click Here</asp:LinkButton>
Purely Server-Side Approach
Instead of a LinkButton, you might want to consider using a HyperLink or <a> tag as you aren't going to be doing anything with your code-behind:
<asp:HyperLink ID="btnSubmit" runat="server" NavigateUrl="Table.aspx" Text="Navigate"></asp:HyperLink>
Then you can use the NavigateUrl property, which you might want to consider setting within your code-behind :
// This will set up your Navigation URL as expected
btnSubmit.NavigateUrl = String.Format("Table.aspx?parameter={0}",ddlCarrier.SelectedItem.Text);
If you use this approach, you may want to explicitly set that a PostBack occurs when your DropDownList changes so that this value will consistently be correct :
<asp:DropDownList ID="dllCarrier" runat="server" AutoPostBack="True" ...>
Client-Side Approach
However, if you are expecting to be able to change this to reflect the current value of your Carrier DropDownList without a PostBack, then you'll likely need to resort to Javascript to populate the value prior to actually navigating :
<!-- Set your base URL within the method and append the selected value when clicked -->
<asp:Button ID="Example" runat="server" OnClientClick="ClientSideNavigate('Table.aspx'); return false;" Text="Navigate"></asp:Button>
<script>
function ClientSideNavigate(url) {
// Get the selected element
var e = document.getElementById('<%= ddlCarrier.ClientID %>');
// Navigate
window.location.href = url + '?parameter=' + e.options[e.selectedIndex].value;
}
</script>
Or you could just avoid ASP.NET Controls altogether and just use an <button> tag :
<button onclick="ClientSideNavigate('Table.aspx'); return false;">Navigate</button>
<script>
function ClientSideNavigate(url) {
// Get the selected element
var e = document.getElementById('<%= ddlCarrier.ClientID %>');
// Navigate
window.location.href = url + '?parameter=' + e.options[e.selectedIndex].value;
}
</script>
You need to handle TextChanged or SelectedIndexChanged event for ddlCarrier and properly set href property of btnSubmit to include ddlCarrier.Text.

How to get dropdown list selected value in Label without using autopostback and update panel in asp.net

How to get dropdown list selected value in Label without autopostback and update panel in asp.net. i want the client side scripting for this code
i have the following code :-
protected void DropDownList1_TextChanged(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue;
// DropDownList1.Attributes["onclick"] =
//"Label1.Text=this.options[this.selectedIndex].value";
}
If you don't want to use jquery (not everyone does! :) ) you can do it with standard javascript
<script language="javascript" type="text/javascript">
function setLabelText() {
var dropdown = document.getElementById("DropDownList1");
document.getElementById("Label1").innerHTML = dropdown.options[dropdown.selectedIndex].text;
}
</script>
<asp:DropDownList ID="DropDownList1" ClientIDMode="Static" runat="server" AutoPostBack="false" onchange="setLabelText();">
<asp:ListItem Value="1" Text="One" />
<asp:ListItem Value="2" Text="Two" />
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Label" ClientIDMode="Static"></asp:Label>
In your CS code, add an attribute such as:
ddlMyDrop.attributes.add("onchange","SetLabel(this,lblCtrl)");
In your JS code...
function SetLabel(sender, target){
$(target).val($(sender).val());
}
This assumes you reference jQuery.
You can do this fairly easily with jQuery. Label's turn into span and DropDownList into select on client side. Keep in mind that asp.net loves to append strings to the resultant content id's, e.g. MainContent_...
$(document).ready(function () {
$('#MainContent_DropDownList1').change(function () {
try {
$('#MainContent_Label1').text($(this + "option:selected").text());
} catch (err) {
alert(err);
}
});
});
Not using jQuery or Javascript as this is a fix of an existing site and it was not designed that way. Well I have gotten to a point where when the DropDownList is selected and does it's postBack I do my logic of setting the textBox readOnly status to true or false. the problem I have now is the the selectValue is not consistant. Wht it show in the selct field is not what is posted back to the page. Say I have None, 5.00, 10.00, 15.00, 20.00 as my choices to choose. I first choose 10.00 and it posts back None then I choose 20.00 it shows 10.00. It posts back the prior select value. the entire site is written from the code behind page. the aspx page is completely written from the .vb page. Everything is written into asp tags. here is the code;
If Page.IsPostBack Then
If product_option_is_required > 0 then
myTextBox.ReadOnly= true
Else
myTextBox.ReadOnly= false
End if
For Each child_control As Control In productOptions.Controls
If TypeOf child_control Is DropDownList Then
Dim child_ddl As DropDownList = child_control
tempName = products.getProductDependant("product_option_name",product_option_id)
tempSelectText = products.getProductSelectDependant("product_option_detail_name",child_ddl.SelectedValue)
priceDependant.Text ="here" & child_ddl.ID & " " & child_ddl.SelectedIndex & " " & child_ddl.SelectedValue & " --" & tempSelectText
If child_ddl.Text = "None" then
myTextBox.ReadOnly = true
myTextBox.Text = "If selected above enter name"
Else
myTextBox.ReadOnly = false
myTextBox.Text = ""
End if
End If
next
End if

Using onCheckedChanged with PopupControlExtender and want to prevent popup when unchecking

I am still reasonably new to this and have tried to find an answer, so hopefully I am not repeating this.
I am using ASP.NET and have a checkbox control that brings up a popup box when it's changed, using the onCheckedChanged method. This popup box has some info in it and a 'Close' button which successfully closes the popup.
What I want is to prevent the popup appearing if the checkbox is being unchecked. I currently have the onCheckedChanged calling a code behind method which cancels the extender call if the control is not checked, but the popup quickly appears before it is closed. How can I prevent it this?
This is the appropriate page code:
<div class="row" id="divDDMandate" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:CheckBox ID="chkDDMandate" Width="20px" Visible="true" runat="server" AutoPostBack="true"
OnCheckedChanged="clientchkDDMandateChanged(this);" on />
<asp:Literal ID="ltlDDMandate" runat="server">Direct Debit Mandate (by post)</asp:Literal>
<asp:PopupControlExtender ID="chkDDMandate_PopupControlExtender" runat="server"
DynamicServicePath="" Enabled="true" PopupControlID="PanelDDMandateDownload"
TargetControlID="chkDDMandate"
Position="Bottom" OffsetX="-20" OffsetY="10" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
...and this is my code behind method:
protected void chkDDMandateChanged(object sender, EventArgs e)
{
//Cancel the panel if unchecking
if ((!chkDDMandate.Checked) && chkDDMandate_PopupControlExtender.Enabled)
{
chkDDMandate_PopupControlExtender.Cancel();
}
}
I would be grateful for any help.
Cheers
Remove AutoPostBack="true" from the chkDDMandate checkbox and add script below after the ScriptManager control:
<script type="text/javascript">
function pageLoad() {
var extender = $find("<%= chkDDMandate_PopupControlExtender.ClientID %>");
extender.remove_showing(onPopupShowing);
extender.add_showing(onPopupShowing);
}
function onPopupShowing(sender, args) {
var checkBoxChecked = $get("<%= chkDDMandate.ClientID %>").checked;
args.set_cancel(!checkBoxChecked);
}
</script>
After Yuriy provided me with the event handler, I had to resort to using hidden fields to keep track of the visibility of the popup and the checkbox.
This was because I didn't want the popup to appear when the tick was being removed and the fact that the onClick method used the setting the checkbox control was being set to, whereas the onShowing method was using the current visible setting of the control. I had to use the hidden fields to keep the visibilty settings and update them at the time I wanted.
I'm surprised that the _visible property of the popup extender was always set to 'false', so I couldn't use that either.
This may be a bit of a hack, but this is my current javascript code for anyone that is interested:
<script type="text/javascript">
function pageLoad() {
// Attach an event handler for over-riding the showing Popup.
var extender = $find("PopupControlExtenderBehaviorID");
extender.remove_showing(onPopupShowing);
extender.add_showing(onPopupShowing);
// Initialise the hidden fields based on the page status after refresh.
var hfPopup = $get("ctl00_body_PopupVisibleID");
var hfCheckbox = $get("ctl00_body_CheckboxChecked");
// Popup will always be hidden on page refresh
hfPopup.value = "Hidden";
hfCheckbox.value = $get("ctl00_body_chkDDMandate").checked;
}
function onPopupShowing(sender, args) {
// This function will over-ride the Popup showing if applicable.
var popupVisible = $get("ctl00_body_PopupVisibleID");
var checkboxChecked = $get("ctl00_body_CheckboxChecked");
// If Popup hidden and 'tick' being taken out of the Checkbox, don't show the Popup.
if (popupVisible.value == "Hidden" && checkboxChecked.value == "true") {
args.set_cancel(true);
}
else if (popupVisible.value == "Hidden") {
popupVisible.value = "Visible";
}
else {popupVisible.value = "Hidden";}
}
function OnClientClickCheck(o) {
// This function will set the Hidden field value of Checkbox.
// This is because when the OnClick method reads the control checkbox value it uses the value it's
// being set to; whereas, the onPopupShowing method uses the value it is currently displaying!
var pce = $find('PopupControlExtenderBehaviorID');
var checkboxChecked = $get("ctl00_body_CheckboxChecked");
var isChecked = o.checked;
if (isChecked) {
// isChecked is what it is being changed to...
checkboxChecked.value = "false";
}
else {
checkboxChecked.value = "true";
}
pce.showPopup();
}
</script>
Thanks for the help in getting here.

Change color of text box with CustomValidator

I am creating some text boxes at runtime and I would like to change the color of the text box if the text box has been left blank
and the user submits the form.
I am using the code behind approach, this is the code I wrote in the .aspx.cs file
textBoxObj is the text box object that I create at runtime and it is the object on which I want the empty validation.
CustomValidator customValidatorObj = new CustomValidator();
customValidatorObj.ControlToValidate = textBoxObj.ID;
customValidatorObj.ClientValidationFunction = "changeColorofTextBox";
and I wrote a small Javascript snippet within the .aspx file which goes as follows (I haven't yet written the logic to change the color,
just making it not valid for now)
<script type="text/javascript">
function changeColorofTextBox(oSrc, args) {
if (args.Value.length > 0) {
args.IsValid = true;
}
else {
args.IsValid = false;
}
}
</script>
In the submit button click function of the form, I have this check if(Page.IsValid), then submit the form. However, even when the text box is empty,
the form gets submitted. It seems like the function is not even being hit. Do you have any pointers on what I am doing wrong?
I am fine with either client side or server side validation, whichever works.
EDIT
I got the error, I just had to do this
customValidatorObj.ValidateEmptyText = true;
and it started working.. Thank you, I didn't realize that the customValidator class does not try validating if the control is blank.
But I am stuck again :(
In the form, I have many text boxes. Suppose, the user entered text for 3 of the text boxes and left 2 of them blank, how do I find the text box ids so that I can change the color of only the blank ones. or, how can I write code in the javascript to find out the control ID at runtime?
I know we have to do this
document.getElementById(CONTROLIDGOESHERE).style.backgroundColor = "red";
but how I get the CONTROLIDGOESHERE value to pass to the getElementById function?
Any pointers, thanks.
Try setting customValidatorObj.EnableClientScipt = True
Assuming you are running .NET Framework version 4.0 then you could declare your textboxes using ClientIDMode="Static". That way they'll have the same ID client-side and server-side e.g.
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static" />
Then you could trigger client-side validation on a button click by declaring a button like this:
<input type="submit" id="btnSubmit" onclick="ClientSideValidation(); return false;" value="Save"/>
The JavaScript function could look something like this:
<script type="text/javascript">
function ClientSideValidation() {
var txtName = document.getElementById("txtName");
if (txtName.value.length == 0) {
txtName.style.background = "#DE0000";
}
// Check other text boxes...
}
</script>
Thank you guys, I figured it out. This code does the job for me
.aspx.cs
CustomValidator customValidator = new CustomValidator();
customValidator.ControlToValidate = textBox.ID;
customValidator.ClientValidationFunction = "changeColorofTextBox";
customValidator.ValidateEmptyText = true;
customValidator.EnableClientScript = true;
e.Item.Controls.Add(customValidator);
.aspx
<script type="text/javascript">
function changeColorofTextBox(oSrc, args) {
if (args.Value.length > 0) {
args.IsValid = true;
}
else {
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
document.getElementById(ctrlid).style.backgroundColor = "Tomato";
args.IsValid = false;
}
}
</script>

Button onClick doesn't work if it is inside of DIV in ASP.NET

I have a div like as :
<div id="specific">
<table cellpadding="2" border="0">
<tr><td>Choose category</td><td><select id="list_categories" runat="server"></select></td><td><asp:RequiredFieldValidator ControlToValidate="list_categories" runat="server" Display="Static" ErrorMessage="Select category" ID="verify_category"></asp:RequiredFieldValidator></td></tr>
<tr><td>Link name : </td><td><asp:TextBox ID="link_name" runat="server"></asp:TextBox></td><td><asp:RequiredFieldValidator ControlToValidate="link_name" runat="server" Display="Static" ErrorMessage="Provide a name for link" ID="verify_link_name"></asp:RequiredFieldValidator></td></tr>
<tr><td>Link url : </td><td><asp:TextBox ID="link_url" runat="server"></asp:TextBox></td><td><asp:RegularExpressionValidator ID="verify_url" runat="server" ControlToValidate="link_url" Display="Static" ErrorMessage="Invalid link. Must be as http://www.stabiplan.com" ValidationExpression="^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$"></asp:RegularExpressionValidator></td></tr>
<tr><td>Link description</td><td><asp:TextBox ID="link_descr" runat="server"></asp:TextBox></td><td><asp:RequiredFieldValidator ControlToValidate="link_descr" runat="server" ID="verify_descr" Display="Static" ErrorMessage="Provide a link description"></asp:RequiredFieldValidator></td></tr>
<tr><td colspan="2"><center><asp:Button runat="server" ID="add_link_process" Text="Add link" OnClick="add_link_function" /></center></td></tr>
</table>
</div>
and the function from CodeBehind.cs
protected void add_link_function( object sender, EventArgs e ) {
BusinessLayerArcht layer = LoadDataFromBL();
if ( layer.add_link( link_name.Text, link_url.Text, link_descr.Text, list_categories.Value.ToString() ) ) {
messages.Text = "Link added successfully";
LoadTree( tree );
} else {
messages.Text = "Link could not be added !";
}
}
When I click on the button, nothing happens. Why ?
If I remove DIV block and let the code inside the <table>, button click event works.
Thank you
I highly doubt it has anything to do with the div element. Usually, when a button does nothing it's because validation is preventing the postback. To test this, set the CausesValidation property to false on the Button and try again.
Have you tried adding a breakpoint to the add_link_function method to check whether its being triggered at all?
Regarding your validation issue, you can add ValidationGroup to your Validation controls as well as your Button. This way, only validation controls with a matching group name as the triggered button, will be actioned.
may you have to change the property of button " UseSubmitBehavior " to false
This is is a total guess, but it's possible the 'div' is sitting on top of your table and preventing the click getting to the button, you could try some Javascript code like this -
function getActivatedObject(e) {
var obj;
if (!e) {
obj = window.event.srcElement;
} else if (e.srcElement) {
obj = e.srcElement;
} else {
obj = e.target;
}
return obj;
}
function addEventHandler(obj, eventName, handler) {
if (document.attachEvent) {
obj.attachEvent("on" + eventName, handler);
} else if (document.addEventListener) {
obj.addEventListener(eventName, handler, false);
}
}
to work out which element was getting the click event.
Code from - How do I know which element was clicked?
In the properties of that button, set OnClientClick as the name of the function you are calling on "onClick".
It worked for me.

Categories

Resources