How to set grid combo box value in javascript? - javascript

I have combobox in grid itemtemplate how can i set the value in javascript
<telerik:GridTemplateColumn AutoPostBackOnFilter="true"
CurrentFilterFunction="Contains" DataField="FAULT" FilterControlWidth="100%"
HeaderStyle-Width="80px" HeaderText="Fault" ReadOnly="true" ShowFilterIcon="false"
SortExpression="FAULT" UniqueName="FAULT">
<ItemTemplate>
<telerik:RadComboBox ID="cmbFault" runat="server" AllowCustomText="false" HighlightTemplatedItems="true"
Skin="Outlook" Visible="true" Width="70px">
<Items>
<telerik:RadComboBoxItem runat="server" Text="NF" Value="N" />
<telerik:RadComboBoxItem runat="server" Text="VF" Value="V" />
<telerik:RadComboBoxItem runat="server" Text="CF" Value="C" />
<telerik:RadComboBoxItem runat="server" Text="DF" Value="D" />
</Items>
</telerik:RadComboBox>
</ItemTemplate>
<HeaderStyle Width="80px" />
</telerik:GridTemplateColumn>
My java script
function vishali(){
if (difference > 5) {alert("enter into if");
document.getElementById('<%=cmbFault.ClientID %>').value = 'C';
}
else {
alert("enter into else");
document.getElementById('<%=cmbFault.ClientID %>').value = 'S';
}
}
but it is not working it is saying that cmbFault is not found in the context error please help me on this

You can do below javascript code in order to set from javascript.
function setCombo() {
var combo = $find("<%= cmbFault.ClientID %>");
combo.set_text("S");
}
And also you can have a look http://www.telerik.com/help/aspnet-ajax/combobox-client-side-radcombobox.html

To get the control inside GridTemplateColumn do the following.
JS:
function setCombo() {
var grid = $find("<%=RadGrid1.ClientID%>");
var tableView = grid.get_masterTableView();
var items = tableView.get_dataItems();
for(var i = 0; i<items.length; i++){
var rowValues = items[i];
var Textvalue=rowValues.findElement("cmbFault");//access Combobox
}
}

Related

Textbox should be disabled unless a certain option in the dropdown box is selected

Here's my JavaScript code: it's not working
<script language="javascript" type="text/javascript">
function ShowExpenseReport(Expense_Report_ID) {
var width = screen.width;
var leftpad = (width - 740) / 2;
var jsoption = "width=740,height=700,resizable=no,scrollbars=yes,toolbar=no,titlebar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=" + leftpad + ",top=10";
window.open("Documents/ExpenseReport.aspx?Expense_Report_ID=" + Expense_Report_ID, 'win02', jsoption);
return false;
}
function changetextbox() {
if (document.getElementById("ddlItem").value == '3') {
document.getElementById("txtPurpose").disabled = 'true';
} else {
document.getElementById("txtPurpose").disabled = '';
}
}
</script>
Below is the HTML side:
<asp:TemplateField HeaderStyle-CssClass="innerGridHeader" ItemStyle-CssClass="itemPadding"
ItemStyle-Width="150px" HeaderStyle-VerticalAlign="Top" FooterStyle-VerticalAlign="Top">
<HeaderTemplate>
Item
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblItem" Visible="false" runat="server" Text='<%#Eval("Item_Description") %>'></asp:Label>
<asp:Label ID="lblItemID" Visible="false" runat="server" Text='<%#Eval("Item_ID") %>'></asp:Label>
<asp:DropDownList ID="ddlItem" Width="140px" runat="server" onChange="changetextbox()" CssClass="combobox">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="innerGridHeader" ItemStyle-CssClass="itemPadding"
ItemStyle-Width="260px" HeaderStyle-VerticalAlign="Top" FooterStyle-VerticalAlign="Top">
<HeaderTemplate>
Purpose
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblPurpose" runat="server" Width="240px" Text='<%#Eval("Purpose") %>'></asp:Label>
<asp:TextBox ID="txtPurpose" runat="server" Width="240px" CssClass="inputbox" Text='<%#Eval("Purpose") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPurpose" runat="server" ErrorMessage="Enter Purpose"
ControlToValidate="txtPurpose" Display="None" ValidationGroup="NER" SetFocusOnError="True">
</asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="vcePurpose" runat="server" TargetControlID="rfvPurpose"
PopupPosition="BottomRight" WarningIconImageUrl="~/Library/Images/exclamation.png" />
</ItemTemplate>
</asp:TemplateField>
I just want to disable the textboxes when the user chooses entertainment from the dropdown which has the value 3 in the database.
I believe what you are trying to do is disable/enable a textbox field on the basis of select value. A proper way followed in ASP is as follows, try this:
onchange="DisableTextBox();"
<script language=javascript>
function DisableTextBox() {
var dropDown = document.getElementById('<%=DropDown.ClientID%>');
if (dropDown.selectedIndex = ValueTocompare) {
document.getElementById('<%=txtBoxID.ClientID%>').disabled = disabled;
} else {
document.getElementById('<%=txtBoxID.ClientID%>').disabled = '';
}
}
</script>
if this doesn't work out for you, try using this fiddle:
http://jsfiddle.net/SurajMindfire/zxvfcvq0/
This will help you:
dropdown is there contain YES and No value(by default yes),
there is text box, when user select YES value from dropdown textbox will enabled but when select No value then textbox get desabled.
astric is id for validation of textbox
function EnableDisableInputField(customerNarration) {
var selectedValue = customerNarration.options[customerNarration.selectedIndex].value;
var txtOther = document.getElementById("customisedNarration");
txtOther.disabled = selectedValue == 'N' ? true : false;
document.getElementById("asterisk").innerHTML = "";
if (!txtOther.disabled) {
txtOther.focus();
document.getElementById("asterisk").innerHTML = "*";
}
var checkError = document.getElementById("customisedNarration_box").style = "display: none";
}
<div class="form-group ">
<label class="floatinglabel"><sup class="text-red">*</sup> Customer Narration required</label>
<div class="selectwrapper">
<select class="form-control" id="customerNarration" name="customerNarration" onchange="EnableDisableInputField(this)" onfocus="hideerrmsgdelayed('customerNarration')">
<option value="Y">Yes</option>
<option value="N">No</option>
</select>
</div>
<span class="inputError" id="customerNarrationReq_box"><%=siteValidation.getErrorMessage("customerNarration")%></span>
</div>
<div class="form-group ">
<label class="floatinglabel"><sup class="text-red" id="asterisk"></sup> Customised Narration </label>
<input type="text" class="form-control" name="customisedNarration" id="customisedNarration" onfocus="hideerrmsgdelayed('customisedNarration')" maxlength="50" />
<span class="inputError" id="customisedNarration_box"><%=siteValidation.getErrorMessage("customisedNarration")%></span>
</div>

Error: The name 'RGGSTAcCode' does not exist in the current context

In one of the webpage, I have RadGrid inside FormView Control
i.e., as below markup:
<asp:FormView ID="fvIPRForm" runat="server" DefaultMode="Insert" DataKeyNames="RequestID"
DataSourceID="odsIPRForm" EnableModelValidation="True" OnItemInserting="fvIPRForm_ItemInserting"
OnDataBound="fvIPRForm_DataBound" OnItemUpdating="fvIPRForm_Updating" OnItemCommand="fvIPRForm_ItemCommand">
<%-- Create New IPR--%>
<InsertItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</InsertItemTemplate>
<%-- Edit IPR--%>
<EditItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</EditItemTemplate>
<%-- View IPR--%>
<ItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</ItemTemplate>
</asp:FormView>
Now, I try to get the RadGrid -- EditItemTemplate -- Button control
inside JavaScript to make it visible true/false based on text length that user enter in RadComboBox.
Below is my JavaScript:
<script lang="javascript" type="text/javascript">
function OnClientTextChange(sender, eventArgs) {
//alert("You typed " + sender.get_text());
var len = sender.get_text().length;
alert(len);
var form = $find("<%#RGGSTAcCode.ClientID%>").get_masterTableView();
alert(form);
}
</script>
When I run my web page, I always get below error:
The name 'RGGSTAcCode' does not exist in the current context
I tried to change the JavaScript code as below:
var form = document.getElementById('<%=fvIPRForm.FindControl("RGGSTAcCode").ClientID%>');
var masterTable = form.get_masterTableView();
alert(masterTable);
but then I get [object Object] in "alert". What is wrong in my code?
Edit
Tried below solution, all working except Buttons are not disabled/enabled inside if/else:
function onTextChange(sender, args) {
//alert("You typed " + sender.get_text());
var len = sender.get_text().length;
alert(len);
var comboID = sender.get_id();
var btnSearchID = comboID.replace("ddlAccountCode", "btnSearch");
alert("Alert 1: " + btnSearchID); //getting : contentplaceholder_fviIPRForm_RGGSTAcCode_btnSearch
var btnCtrl = $get(btnSearchID);
alert("Alert 2: " + btnCtrl); //getting : [object HTMLInputElement]
if (len > 5)
{
alert("greater");
btnCtrl.set_enabled(true);
btnsearch.set_enabled(true); // enable search button
}
else
{
alert("less");
btnCtrl.set_enabled(false);
btnsearch.set_enabled(false); // disable search button
}
}
This might be the answer you want....
Not the best but is working..
.aspx
<asp:FormView ID="fv" runat="server" DefaultMode="Insert" OnDataBound="fv_DataBound">
<InsertItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server"
SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
<telerik:RadGrid ID="RadGrid1" runat="server"
AutoGenerateColumns="false"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView>
<Columns>
<telerik:GridTemplateColumn HeaderText="Acc">
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Eval("Acc") %>'></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode"
runat="server" Height="200" Width="260"
AllowCustomText="true"
OnClientTextChange="onTextChange">
<Items>
<telerik:RadComboBoxItem Text="Gg" />
<telerik:RadComboBoxItem Text="Gg1" />
<telerik:RadComboBoxItem Text="Gg3" />
</Items>
</telerik:RadComboBox>
<telerik:RadButton ID="btnSearch" runat="server" Text="Search" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</InsertItemTemplate>
</asp:FormView>
Javascript
<telerik:RadCodeBlock ID="rcb" runat="server">
<script type="text/javascript">
function onTextChange(sender, args) {
var grid = $find('<%=fv.FindControl("RadGrid1").ClientID %>');
var gridMasterData = grid.get_masterTableView();
var dataItem = gridMasterData.get_dataItems();
var length = dataItem.length;
// Loop
for (var i = 0; i < length; i++) {
// Find Control
var comboBox = dataItem[i].findControl("ddlAccountCode");
// Check
if (comboBox != undefined) {
if (sender.get_id() == comboBox.get_id()) {
// Find Button
var btn = dataItem[i].findControl("btnSearch");
var item = sender.get_text();
// Check
if (item.length > 5) {
if (btn != undefined) btn.set_visible(true);
}
else btn.set_visible(false);
break;
}
else
continue;
}
}
}
</script>
</telerik:RadCodeBlock>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
dt.Columns.Add("Acc");
dt1.Columns.Add("a");
// Loop
for (int i = 0; i < 2; i++)
dt.Rows.Add("a " + i);
dt1.Rows.Add("AAAA");
ViewState["Data"] = dt;
// Bind
fv.DataSource = dt1;
fv.DataBind();
dt.Dispose();
dt1.Dispose();
}
}
protected void fv_DataBound(object sender, EventArgs e)
{
// FindControl
RadGrid RadGrid1 = fv.FindControl("RadGrid1") as RadGrid;
// Check
if (RadGrid1 != null)
{
RadGrid1.DataSource = ViewState["Data"] as DataTable;
RadGrid1.DataBind();
}
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid rg = fv.FindControl("RadGrid1") as RadGrid;
// Check
if (rg != null)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
}
Below code is working fine based on my requirement:
function onTextChange(sender, args) {
var len = sender.get_text().length;
//alert(len);
var comboID = sender.get_id();
var btnSearchID = comboID.replace("ddlAccountCode", "btnSearch");
var btnCtrl = document.getElementById(btnSearchID);
if (len >= 5)
{
btnCtrl.disabled = false;
//btnCtrl.style.display = "";
}
else
{
btnCtrl.disabled = true;
//btnCtrl.style.display = "none";
}
}

Validation Group of many ASPxTextBox in the same time

I am validating some .net textboxes in javascript on focusout via regular expression:
ValidationExpression="[0-9]+(\.[0-9][0-9]?)?"
for all text boxes.
If isValidate, button enabled = true else button enabled = false
but my code doesn't work:
<dx:ASPxTextBox ID="tbxAcPart" runat="server" Width="95px" ClientIDMode="Static">
<ClientSideEvents Validation="function(s, e) {ValidTextBox(s);}" />
<ValidationSettings ErrorDisplayMode="Text" EnableCustomValidation="true" SetFocusOnError="true" ValidationGroup="Apply" Display="Dynamic" ErrorTextPosition="Bottom" >
<ErrorFrameStyle Font-Size="Smaller"/>
<RegularExpression ValidationExpression="[0-9]+(\.[0-9][0-9]?)?" ErrorText="Numeric !" />
<RequiredField IsRequired="true" />
</ValidationSettings>
</dx:ASPxTextBox>
<dx:ASPxTextBox ID="tbxMpPart" runat="server" Width="95px" ClientIDMode="Static">
<ClientSideEvents Validation="function(s, e) {ValidTextBox(s);}" />
<ValidationSettings ErrorDisplayMode="Text" EnableCustomValidation="true" SetFocusOnError="true" ValidationGroup="Apply" Display="Dynamic" ErrorTextPosition="Bottom" >
<ErrorFrameStyle Font-Size="Smaller"/>
<RegularExpression ValidationExpression="[0-9]+(\.[0-9][0-9]?)?" ErrorText="Numeric !" />
<RequiredField IsRequired="true" />
</ValidationSettings>
</dx:ASPxTextBox>
function ValidTextBox(s) {
if (s.GetIsValid()) {
decimalErr.SetText('');
}
else {
decimalErr.SetText(s.GetErrorText());
var t = document.getElementsById("btApply");
t.disabled = true;
this.focus();
}
}
If you use server control you need to use ctl.ClientID
function ValidTextBox(s) {
if (s.GetIsValid()) {
decimalErr.SetText('');
}
else {
decimalErr.SetText(s.GetErrorText());
var t = document.getElementById("<%= btApply.ClientID %>");
t.disabled = true;
this.focus
}
}

While calculating total of gridview cell using javascript and jquery getting error

I am calculating the total of GridView cells using java script and jquery. But, I am always getting this error while compiling.
The name 'total' does not exist in the
current context
Inside GridView code:
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Total" Font-Bold="true">
</asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2" >
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" class="calculate"
onchange="calculate()"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="total" runat="server"></asp:TextBox>
</FooterTemplate>
javascript and jquery code:
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"
type="text/javascript">
<script language="javascript" type="text/javascript">
function calculate()
{
var txtTotal = 0.00;
//var passed = false;
//var id = 0;
$(".calculate").each(function (index, value) {
var val = value.value;
val = val.replace(",", ".");
txtTotal = MathRound(parseFloat(txtTotal) + parseFloat(val));
});
document.getElementById("<%=total.ClientID %>").value = txtTotal.toFixed(2);
}
function MathRound(number) {
return Math.round(number * 100) / 100;
}
</script>
how can I solve this issue any help pls.
You can't access controls inside templated controls like GridView that easily. Create some variable to hold total.ClientID so that jQuery can grab it.
In your aspx:
var totalClientID = TotalClientID;
In codebehind:
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Footer)
{
TotalClientID = ((TextBox)e.Row.FindControl("total")).ClientID;
}
}
<script language="javascript" type="text/javascript">
function Calculate() {
var grid = document.getElementById("<%=grid.ClientID%>");
var sum = 0;
for (var i = 1; i < grid.rows.length; i++) {
var Cell = grid.rows[i].getElementsByTagName("input");
if (!Cell[4].value) {sum += 0; } else { sum += parseFloat(Cell[0].value);}
}
alert(sum);
}
</script>
<asp:TemplateField HeaderText="Current payment" >
<ItemTemplate>
<asp:TextBox ID="txtvalue" runat="server" Width="70px" BorderStyle="None" onkeyup="Calculate();" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="120px" />
</asp:TemplateField>`enter code here`

validate radiobuttonlist in a gridview using javascript

I am trying to validate that each radiobuttonlist has been selected. the radiobuttonlist is dynamically created from a sql database. The following line errors out "if (MyRadio[j].checked) {", the error is "checked' is null or not an object". The following is the code. Thank you
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
<cc1:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0" CssClass="ajax__myTab" Width="100%" ScrollBars="Horizontal">
<cc1:TabPanel ID="TabPanel1" runat="server" HeaderText="" Enabled="true">
<HeaderTemplate>Main</HeaderTemplate>
<ContentTemplate>
<table cellpadding="3" cellspacing="1">
<tr>
<td style="text-align: right">Audit Status:</td>
<td>
<asp:DropDownList ID="ddlAuditStatus" runat="server">
<asp:ListItem>InProgress</asp:ListItem>
<asp:ListItem>Completed</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="TabPanel2" runat="server" HeaderText="" Enabled="true">
<HeaderTemplate>Questions</HeaderTemplate>
<ContentTemplate>
<asp:GridView ID="GridViewQuestions" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="5" CellSpacing="1" DataKeyNames="Pkey" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblQuestion" runat="server"></asp:Label>
<asp:HiddenField ID="hdnPkey" runat="server" Value='<%# Bind("Pkey") %>' />
<asp:HiddenField ID="hdnRequiresAnAnswer" runat="server" Value='<%# Bind("RequiresAnAnswer") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" Visible="false">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
<asp:ListItem>N/A</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<HeaderStyle Width="130px" />
<ItemStyle Width="130px" />
</asp:TemplateField>
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Silver" Font-Bold="True" ForeColor="Black" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
<script type="text/javascript">
function fcnUpdateMain() {
var MyStatus = document.getElementById("<%=ddlAuditStatus.ClientID%>").value
var grid = document.getElementById("<%= GridViewQuestions.ClientID %>");
if (grid.rows.length > 0) {
for (i = 2; i < grid.rows.length + 1; i++) {
if (i < 10) {
i = "0" + i
} else {
i = i
}
var MyReqAnswer = document.getElementById("ctl00_ContentPlaceHolder2_TabContainer1_TabPanel2_GridViewQuestions_ctl" + i + "_hdnRequiresAnAnswer").value
var MyRadio = document.getElementById("ctl00_ContentPlaceHolder2_TabContainer1_TabPanel2_GridViewQuestions_ctl" + i + "_RadioButtonList1")
if (MyStatus == "Completed") {
if (MyReqAnswer == "Yes") {
var options = document.getElementsByTagName("input")
for( x = 0; x < options.length; ++x ) {
if(options[x].type == "radio") {
for (var j = 0; j < MyRadio.length; j++) {
if (MyRadio[j].checked) {
} else {
alert("You must select an answer for all questions.")
document.getElementById("ctl00_ContentPlaceHolder2_TabContainer1_TabPanel2_GridViewQuestions_ctl" + i + "_ddlProductInterest").focus()
return false;
}
}
}
}
}
}
}
}
}
</script>
I think you've already realised that RadioButtonList controls are rendered as a <table> with each radio button as an <input> within that table. Therefore getting a handle on RadioButtonList1 and trying to access it as an array using MyRadio[j] isn't going to work.
I think the following line:
var options = document.getElementsByTagName("input")
Should instead read:
var options = MyRadio.getElementsByTagName("input")
That will give you just a collection of the input tags within that RadioButtonList control rather than all those on the page. Once you have that options collection, you shouldn't need to refer to the RadioButtonList control again.
I understand that this is drastically simplified over what you have, but here's an example for you:
<form runat="server">
<asp:RadioButtonList runat="server" id="RadioButtonList1">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
<asp:ListItem>N/A</asp:ListItem>
</asp:RadioButtonList>
<input type="button" onclick="fcnUpdateMain()" value="Click" />
<script type="text/javascript">
function fcnUpdateMain()
{
var MyRadio = document.getElementById("<%=RadioButtonList1.ClientID%>")
var options = MyRadio.getElementsByTagName("input")
var somethingChecked = false;
for( x = 0; x < options.length; ++x )
{
if (options[x].checked)
{
somethingChecked = true;
}
}
if (!somethingChecked)
{
alert("You must select an answer for all questions.")
return false;
}
}
</script>
</form>

Categories