I have a User Control with a Datagrid. I need to check some Textboxes within by calling my Javascript File doing the compare when the user will Save its modifications. (it will trigger my validator, if it is wrong a popup will show)
My ASPX:
<script type="text/javascript" src='/scripts/production_cost.js'></script>
<ContentTemplate>
<asp:DataGrid ID="ProdCostGrid" runat="server" AutoGenerateColumns="False" BorderColor="#f0f0f0" BorderStyle="None" BorderWidth="0px" CellPadding="0">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<Columns>
<asp:BoundColumn Visible="False" DataField="Id" HeaderText="Id"></asp:BoundColumn>
<asp:TemplateColumn>
<ItemTemplate>
Amount: <asp:TextBox ID="ProductionCostLineField" Text='<%# ToText(Eval("ProductionCostEuro")) %>'
TabIndex="24" runat="server" Width="80px" MaxLength="13"></asp:TextBox> EUR
</ItemTemplate>
<ItemStyle Width="170px" HorizontalAlign="Right"></ItemStyle>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
//here I am suppose to put my Validator
<asp:CustomValidator ID="AmountCustomValidator" runat="server" Display="None" ErrorMessage="Amount must be filled" ClientValidationFunction="ValidateAmount" />
</ContentTemplate>
My Javascript in a different folder :
function ValidateAmount(source, args) {
args.IsValid = true;
$('input[id*="ProductionCostLineField"]').blur(function () {
var amount = this.value;
$('input[id*="ProductionCostInvoiceToLineField"]').each(function () {
var textInvoicedBy = this.value;
if (amount == '' || amount == '0') {
} else {
if (this.value != '' || amount == '' || amount == '0') {
args.IsValid = true;
}
if ((amount != '' || amount != '0') && textInvoicedBy == '') {
alert("You must inform the field 'Invoiced By'");
args.IsValid = false;
}
}
});
});
}
Related
Guys I have a form like this(an aspx page): http://prntscr.com/8tmvge . I wrote validations each of them,And it is working properly. If user enter numeric value in name textbox (ex),it gives error and I'm clearing that textbox(only that textbox) but enter the accurate value and pressing send button, none of the validations and click events doesn't triggered.I couldn't understand how can I fix this? code is below:
Ekle.aspx:
<form id="form1" runat="server">
<div id="ekle">
<asp:Table ID="Table1" runat="server">
<asp:TableRow ID="TableRow1" runat="server">
<asp:TableCell>Id:</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txt1" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txt1" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow2" runat="server">
<asp:TableCell>Name:</asp:TableCell><asp:TableCell>
<asp:TextBox ID="txt2" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txt2" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow3" runat="server">
<asp:TableCell>Surname:</asp:TableCell><asp:TableCell>
<asp:TextBox ID="txt3" runat="server"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txt3" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow4" runat="server">
<asp:TableCell>Sex:</asp:TableCell>
<asp:TableCell>
<span id="spanddl">
<asp:DropDownList ID="ddl1" runat="server">
<asp:ListItem Value="Bay">Bay</asp:ListItem>
<asp:ListItem Value="Bayan">Bayan</asp:ListItem>
</asp:DropDownList>
</span>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow5" runat="server">
<asp:TableCell>Email:</asp:TableCell><asp:TableCell>
<asp:TextBox ID="txt5" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txt5" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow6" runat="server">
<asp:TableCell>City:</asp:TableCell><asp:TableCell>
<asp:TextBox ID="txt6" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txt6" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow7" runat="server">
<asp:TableCell>Age:</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txt7" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txt7" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<input id="ekle_gonder" type="button" value="Gönder" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
</form>
ekle.js :
$(document).ready(function () {
var result = 1;
var id, name, surname, email, city, age;
$("#content").on('click', "#ekle_gonder", function (e) {
var gender = $("#ddl1 option:selected").text();
//var gender = document.getElementById('<%= ddl1.ClientID%>');
//var gender2 = gender.options[gender.selectedIndex].value;
check();
var obj = {};
obj.Id = id;
obj.Name = name;
obj.Surname = surname;
obj.Sex = gender;
obj.Email = email;
obj.City = city;
obj.Age = age;
if (result == 1) {
$.ajax({
type: "post",
url: "ShowRecord.aspx/ekle_func",
contentType: "application/json;charset:utf-8",
data: JSON.stringify(obj),
dataType: "json",
success: onSuccess,
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
//complete:printAgain()
});
}
});
function check() {
var mailregex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var textregex = /^[A-Za-z çğıöşü]{1,25}$/;
var numregex = /(^\d+$)/;
id = $("#txt1").val();
name = $("#txt2").val();
surname = $("#txt3").val();
email = $("#txt5").val();
city = $("#txt6").val();
age = $("#txt7").val();
if ((numregex.test(parseInt(id)) == false) || (parseInt(id) < 0)) {
open_error_box("#ekle_id_error", "#txt1");
}
if ((name == '') || (textregex.test(name) == false)) {
open_error_box("#ekle_name_error", "#txt2");
}
if ((surname == '') || (textregex.test(surname) == false)) {
open_error_box("#ekle_surname_error", "#txt3");
}
if ((email == '') || (mailregex.test(email) == false)) {
open_error_box("#ekle_email_error", "#txt5");
}
if ((city == '') || (textregex.test(city) == false)) {
open_error_box("#ekle_city_error", "#txt6");
}
if ((numregex.test(parseInt(age)) == false) || (parseInt(age) < 0) || (parseInt(age) > 100)) {
open_error_box("#ekle_age_error", "#txt7");
}
return result;
}
function open_error_box(error_name, name) {
$(error_name).dialog("open");
$(name).val('');
result = 0;
}
function onSuccess() {
$("#txt1").val('');
$("#txt2").val('');
$("#txt3").val('');
$("#txt4").val('');
$("#txt5").val('');
$("#txt6").val('');
$("#txt7").val('');
}
$(function () {
$("#ekle").dialog();
$("#ekle_id_error ,#ekle_name_error, #ekle_surname_error, #ekle_email_error, #ekle_city_error, #ekle_age_error").dialog(
{
autoOpen: false,
buttons: [{
text: "OK",
click: function () { $(this).dialog("close"); }
}]
});
});
});
By the way the id='content' selector is in another page.I'm loading Ekle.aspx into a div(in ShowRecord.aspx) when pressed 'ekle' button(inside ShowRecord.aspx again).ANd error dialog boxes are in ShowRecord.aspx also.
When you clear the textbox, you should change the result value as 1. Your result value just set as 1, when the document is ready. However, if there is something is wrong, you set it as 0, then you never change it as 1.
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";
}
}
I have to invoke ImageButton (in repeater footer) click event from jQuery on response to ajax modalpopupextender button. I tried the below code but it's not working. It doesn't throw any error but PostBack is not happening.
var isCurrentPortalFormSaveClicked = false;
var controlsValuesOnload = '';
var controlsValuesWhileExit = '';
window.onbeforeunload = beforeUnload;
window.onload = getValues;
function getValues() {
controlsValuesOnload = $('form').serialize();
}
function beforeUnload() {
if (isCurrentPortalFormSaveClicked == true) return;
controlsValuesWhileExit = $('form').serialize();
if (controlsValuesOnload != controlsValuesWhileExit) {
return "Your changes have not been saved. To stay on the page so that you can save your changes, click Cancel.";
}
}
function confirmExit(callBackMethod, saveButtonId) {
controlsValuesWhileExit = $('form').serialize();
if (controlsValuesOnload != controlsValuesWhileExit) {
return ShowUnSavedChangesWarning(callBackMethod,saveButtonId);
}
else {
window.open('', '_self', '');
window.close();
return false;
}
}
function ShowUnSavedChangesWarning(callBackMethod, saveButtonId) {
saveButtonControl = saveButtonId;
callBack = callBackMethod;
$find('<%= modalPopUpConfirmExitWarning.ClientID %>').show();
return true;
}
function saveFormAndClose() {
HideUnSavedChangesWarning();
if (callBack != '' && callBack != null && callBack != undefined) {
return callBack();
}
else if (saveButtonControl != '' && saveButtonControl != undefined) {//if the control is other than ribbon save and close button.
saveButtonControl.click();
window.open('', '_self', '');
window.close();
}
else if ($('.saveandclose') != null && $('.saveandclose') != '' && $('.saveandclose') != undefined) {
$('.saveandclose')[0].click();
}
return false;
}
function closeForm() {
isCurrentPortalFormSaveClicked = true;
window.open('', '_self', '');
window.close();
return false;
}
function SaveNewNotes() {
//Save Notes
var notes = $('.newNote').first().val();
if (notes != null && notes != "") {
$('.saveNotes')[0].click();
}
return true;
}
ASPX:
<ajax:ModalPopupExtender ID="modalPopUpConfirmExitWarning" CancelControlID="btnCancel"
runat="server" PopupControlID="panelConfirmExitWarning" TargetControlID="btnHiddenConfirmExitWarning"
BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
<asp:Button runat="server" ID="btnHiddenConfirmExitWarning" Style="display: none" />
<asp:Panel ID="panelConfirmExitWarning" runat="server" Style="display: none" CssClass="ModalWindow">
<div class="window_header">
<span id="spanSubscirptionWindowHeader" runat="server" />
</div>
<div class="window_body">
<img src="../Images/Icon_Warning_New.png" />
<span id="spanConfirmExitExpiryWarning" runat="server" />
</div>
<div class="window_footer" align="right">
<asp:Button ID="btnSave" runat="server" Text="<%$ Resources:DealerWebPortal, DWP_SPAN_Ribbon_Save %>"
OnClientClick="return saveFormAndClose();" CssClass="popUp_button" />
<asp:Button ID="btnDontSave" runat="server" Text="<%$ Resources:DealerWebPortal, DWP_BTN_Page_Home_DontSave %>"
OnClientClick="return closeForm();" CssClass="popUp_button" />
<asp:Button ID="btnCancel" runat="server" Text="<%$ Resources:DealerWebPortal, DWP_BTN_Page_DealerEmailSubscription_Cancel %>"
CssClass="popUp_button" />
</div>
</asp:Panel>
Button (to trigger modalpopupextender):
<a id="lnkClose" class="close" runat="server" onclick="isCurrentPortalFormSaveClicked=true;return confirmExit(SaveNewNotes,null);"> </a>
Repeater:
<asp:Repeater runat="server" ID="rptrCaseNotes" OnItemCommand="rptrCaseNotes_ItemCommand">
<FooterTemplate>
<table>
<tr style="width: 650px">
<td style="vertical-align: middle; width: 50px">
<asp:ImageButton ID="AddNote" Width="16px" Height="16px" ImageUrl="~/Images/112_Plus_Blue_32x32_72.jpg"
runat="server" CommandName="Add" OnClick="OnAddNotes" OnClientClick="isCurrentPortalFormSaveClicked=true" CssClass="saveNotes" />
</td>
<td style="width: 600px">
<asp:TextBox runat="server" ID="NewNotes" Rows="6" Width="600px" Height="80px" TextMode="MultiLine"
MaxLength="2000" CssClass="newNote" />
</td>
</tr>
</table>
</FooterTemplate>
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`
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>