How to Validate Drop-down inside GridView using JavaScript - c#

I am trying to validate a drop down inside a gridview on a button click. If the drop down has no selection then i want to fire the javascript but the code is not firing at all. I am not sure what am i doing wrong here so please help. thanks.
Here is the button code in the aspx file:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="183px" Visible="true"
onclick="btnSubmit_Click"
OnClientClick="return validate();"
Font-Bold="True" Font-Size="Medium" Height="30px"
style="margin-right: 1px; margin-left: 185px;" ForeColor="#336699" />
here is the javascript in the head section of my page:
<script type="text/javascript">
function validate() {
var flag = true;
var dropdowns = new Array(); //Create array to hold all the dropdown lists.
var gridview = document.getElementById('<%=GridView1.ClientID%>'); //GridView1 is the id of ur gridview.
dropdowns = gridview.getElementsByTagName('--'); //Get all dropdown lists contained in GridView1.
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns.item(i).value == '--') //If dropdown has no selected value
{
flag = false;
break; //break the loop as there is no need to check further.
}
}
if (!flag) {
alert('Please select value in each dropdown');
}
return flag;
}
</script>
here is my drop-down in the aspx:
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server" AutoPostBack="false">
</asp:DropDownList>
</ItemTemplate>
here is the code behind for the dropdown
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
ddl_Answer.Items.Insert(0, new ListItem("--"));

How are you trying to select the dropdown using javascript. You probably want this
dropdowns = gridview.getElementsByTagName('select');

Related

Show DropDown in Gridview when specific row checkboox is selected

I want specific row dropdown to be shown when the same row's checkbox is selected. But having problem as all the dropdowns of the grid are shown on one row's checkbox selection.
This is the Grid:
<asp:TemplateField HeaderText="Advertise Id" HeaderStyle-Width="150px" HeaderStyle-Font-Size="14px" HeaderStyle-ForeColor="Black">
<ItemTemplate>
<div style="text-align: left;">
<asp:TextBox runat="server" Width="120px" ReadOnly="true" ID="TextBoxAdvertiseId" Text='<%# Eval("AdvertiseIdName")%>' />
<input type="checkbox" class="CheckBoxImage" onclick="CheckBoxImage()" />
<asp:DropDownList CssClass="DDAdvertise" runat="server" Width="130px" ID="drpdwnadvertiseAdd"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
This is the jquery Code:
function CheckBoxImage() {
var flag = false;
$('.GridLocation input[type="checkbox"]').each(function () {
var checkbox = $('.GridLocation input[type="checkbox"]');
var row = $(this).parent().parent().parent().parent().parent();
if ($(this).is(':checked')) {
flag = true;
$(row).find('.DDAdvertise').show(); // Problem is in .DDAdvertise as it is a classname so it's selecting all the dropdowns
} else {
$(row).find('.DDAdvertise').hide();
}
if (flag) {
$(row).find('.DDAdvertise').show();
}
else {
$(row).find('.DDAdvertise').hide();
}
});
}
Now, the problem is i am using class name (.DDAdvertise) in jquery which is showing all the dropdowns. I want the specific dropdown to be shown whose row's checkbox is selected.

asp.net c# validation

I am trying to create a simple form that uses radio buttons. I set the radio button to AutoPostBack = True, this way if the radio button is true/false, a subpanel is Shown or Hidden. The radio buttons are required fields. I also have a hidden textbox that the value of the selected radio button is inserted and this textbox is what I validate against (empty or not).
Problem 1:
This works until you go to submit and the validation fails. The validation messages show, then when you click on one of the radio buttons with AutoPostBack = True, all the validation disappear. I can resolve this by adding Page.Validate() to the method that runs when the radio button is clicked. But, I do not want the Page.Validate() to run unless the page was already showing validation errors (so it will not re-validate unless the form was already submitted and failed the validation).
As it stands, before the form is submitted and fails validation: when you click on any radio button question, all the other questions requiring validation show the validation error. I am only looking to overcome the AutoPostBack which is clearing all the validation messages that are shown when you had click submit.
Problem 2:
I would like to be able to change the color of the question if it does not pass validation. I added the javascript to override the default .net settings. I got this to work, but only when you click the submit button and not after a RadioButton AutoPostBack.
Currently, When you click submit all the required questions turn red and also display the required validation message. But if you click a radio button to start fixing the validation errors, on the AutoPostBack, the all the questions that were now red in color changes back to the orignal black and the required validation message is still shown. How can I call the Javascript to run again along with the Page.Validation() in the code behind method?
Any help would be greatly appricated! Thanks
Below is an example of the code so far.
ASPX Code:
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableRow>
<asp:TableCell CssClass="question">
<label>4. Have you had an abnormal result from a prenatal test (e.g. amniocentesis, blood test, ultrasound)?</label>
</asp:TableCell>
<asp:TableCell CssClass="answer">
<ul class="selectGroup">
<li>
<asp:RadioButton ID="Q4_true" runat="server" Checked='<%# Bind("Q4_yes") %>' Text="Yes"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" /></li>
<li>
<asp:RadioButton ID="Q4_false" runat="server" Checked='<%# Bind("Q4_no") %>' Text="No"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" />
</li>
<asp:TextBox ID="Q4_validationBox" runat="server" CssClass="hiddenField" Enabled="false"
Text=''></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" EnableViewState="true" ControlToValidate="Q4_validationBox"
Display="Dynamic" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ul>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
Code Behind
protected void RB_QuestionSubPane_YN(object sender, EventArgs e)
{
RadioButton radio_Selected = (RadioButton)sender;
string radio_QuestionID = Convert.ToString(radio_Selected.ID);
(((TextBox)FormView1.FindControl(strQuestionID + "_validationBox")).Text) = radio_Selected.ID.ToString();
Page.Validate();
}
JavaScript
ValidatorUpdateDisplay = function (val) {
var ctl = $('#' + val.controltovalidate);
var eCount = 0;
for (var i = 0; i < Page_Validators.length; i++) {
var v = Page_Validators[i];
if (v.controltovalidate == val.controltovalidate) {
if (!v.isvalid) {
eCount++;
ctl.addClass('validationError');
$('td.question:eq(' + i + ')').addClass('red');
}
};
}
if (eCount > 0) {
ctl.addClass('validationError');
} else {
ctl.removeClass('validationError');
$('td.question:eq(' + i + ')').removeClass('red');
}
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
It sounds like what you really need is custom validation. That way you can fully customize your validation to meet your needs.
Here is a simple example:
<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{
//put your javascript logic here
}
//-->
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="direction" Text="left" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="direction" Text="right" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</div>
</form>
</body>
Server Side
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//validate is successful.
}
}

disable/enable outside asp button control on datalist checkbox checked javascript?

I have a datalist inside that I am using a checkbox, I have 1 asp button and 2 image buttton which is outside of datalist something like this
<asp:DataList ID="dlst1" runat="server" RepeatDirection="Horizontal" OnItemDataBound="dlst1_ItemDataBound" CaptionAlign="Left">
<ItemTemplate>
<asp:ImageButton ID="btnImage" runat="server" />
<asp:CheckBox ID="Chkbox" runat="server" TextAlign="Right" />
</ItemTemplate>
</asp:DataList>
<asp:Button ID="Button1" runat="server" Enabled="false" Text="Delete" />
<asp:ImageButton ID="ibtnok" runat="server" Enabled="false" />
I want to enable the Button1 and ibtok when any one checkbox is checked and disable the Button1 and ibtnok when no checkbox is checked.
someone plz help me how to do that with javascript?
If you are using jquery, you can do it this way:
$("#Chkbox").change(function(){
if($(this).is(':checked'))
{
$('#Button1, #ibtnok').attr('disabled','disabled');
}
else
$('#Button1, #ibtnok').removeAttr('disabled');
})
If there are multiple checkboxes appearing, then you can give those checkboxes a common class, and on every change event, you need to loop through all those elements , or take a count of unchecked/checked checkboxes, and do enable/disable your button.
Looping through each of those checkboxes can be done with $('.your_common_chkbox_class').each(function_to_be_performed);
UPDATE
eg:
$('.your_common_chkbox_class').click(function(){
if($('.your_common_chkbox_class:checked').length > 0)
$('#Button1, #ibtnok').attr('disabled','disabled');
else
$('#Button1, #ibtnok').removeAttr('disabled');
})
Thank you # linuxeasy I have taken you code and modified (checkbox id) and now its working
<script type="text/javascript" language="javascript">
$(function () {
$('.CSSCheck').click(function () {
if ($("[id$='Chkbox']:checked").length > 0) {
$("#<%=Button1.ClientID %>").removeAttr('disabled');
}
else {
$("#<%=Button1.ClientID %>").attr('disabled', 'disabled');
}
});
});
</script>

check/uncheck all checkbox of datalist on button click which is outside of datalist

I hava a datalist in side that I have checkbox
<asp:DataList ID="dlst1" runat="server" RepeatDirection="Horizontal" OnItemDataBound="dlst1_ItemDataBound" CaptionAlign="Left">
<ItemTemplate>
<asp:ImageButton ID="btnImage" runat="server" />
<asp:Label ID="lbl" runat="server"/>
<asp:CheckBox ID="Chkbox" runat="server" TextAlign="Right" />
</ItemTemplate>
</asp:DataList>
I have 2 button
I want to check all the check box when user click on Check All btn, and Uncheck All checkbox when user click on Uncheck All btn, I don't want any post back, how to do it in client side.
I am trying
function CheckOrUncheckAll(isChecked) {
var dataList = document.getElementById('<%= DataList.ClientID %>');
for (var index = 0; index < dataList.rows.length; index++) {
for (var cIndex = 0; cIndex < dataList.rows[index].cells.length; cIndex++) {
dataList.rows[index].cells[cIndex].childNodes[3].checked = isChecked;
}
}
return false;
}
<asp:Button ID="btnCheckAll" runat="server" Text="Check All" OnClientClick="return CheckOrUncheckAll(true)" />
<asp:Button ID="btnUnCheckAll" runat="server" Text="Uncheck All" OnClientClick="return CheckOrUncheckAll(false)" />
its working fine but I don't want to use childNodes[3], because in future in in datalist something got added then I need to change the index.. any jquery to change this function
please try below
function CheckUnCheckAll(checkoruncheck)
{
var list = document.getElementById("<%=dlst1.ClientID%>") ;
var chklist = list.getElementsByTagName("input");
for (var i=0;i<chklist.length;i++)
{
if (chklist[i].type=="checkbox" )
{
chklist[i].checked = checkoruncheck;
}
}
}
call this as
CheckUnCheckAll(true);
or
CheckUnCheckAll(false);
I think, you must use jQuery.
To check:
$("#<%=btnCheckAll.ClientID %>").click(function() {
$("#<%= dlst1.ClientID %> input:checkbox").attr("checked", "checked");
});
To uncheck:
$("#<%=btnUnCheckAll.ClientID %>").click(function() {
$("#<%= dlst1.ClientID %> input:checkbox").removeAttr("checked");
});

Find checkbox and textbox placed inside gridview using javascript

I want to get the value of check box placed inside grid view. if check box is checked, it textbox in that row should be enable and if it is again uncheked, the textbox should get clear and disabled. I asked this question few hours back but still didn't get satisfactory answer.
I tried like this.
//My grid code.
<asp:GridView ID="DeptGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="DeptId" HeaderText="ID"/>
<asp:BoundField DataField="DeptName" HeaderText="Department"/>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="addToCompanyBox" onClick="EnableHODBox()" runat="server" />
</ItemTemplate>
<HeaderTemplate>
Add
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="hodNameBox" runat="server" Width="200px" Enabled="false"></asp:TextBox>
</ItemTemplate>
<HeaderTemplate>
Dept Head
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//My javascript code
<script type="text/javascript">
function EnableHODBox() {
//alert('hello');
var GridView = document.getElementById('<%=DeptGrid.ClientID %>');
//var GridView = document.getElementById('');
var DeptId;
if (GridView.rows.length > 0) {
for (Row = 1; Row < GridView.rows.length; Row++) {
// DeptId = GridView.rows.cell[0];
if (GridView.rows[Row].cell[3].type == "checkbox")
// var chkbox = GridView.rows[Row].cell[3].type == "checkbox"
(GridView.rows[Row].cell[3].type).checked = true;
}
}
}
</script>
This solution is tested and works using only JavaScript (no jQuery is required for this solution!).
1. C# Part (In Page_Load Method)
In Page_Load we need to add a small hack:
foreach(GridViewRow row in YourGridViewControlID.Rows)
{
if (row.RowType == DataControlRowType.DataRow )
{
((CheckBox) row.FindControl("YourCheckBoxID")).Attributes.Add("onchange", "javascript:TextboxAutoEnableAndDisable(" + (row.RowIndex ) + ");");
}
}
This way, we are adding the JavaScript function call on the OnChange event of every CheckBox of our GridView. What is special and we can't achieve through the HTML is that we are passing the Row Index of each one in the JavaScript function, something that we need later.
2. Some important notes for the HTML Part
Make sure that both Checkbox control and Textbox control but more importantly your GridView Control has static id by using the ClientIDMode="Static" as shown bellow:
<asp:CheckBox ID="YourCheckBoxID" runat="server" ClientIDMode="Static"/>
<asp:TextBox ID="YourTextBoxID" TextMode="SingleLine" runat="server" ClientIDMode="Static" />
And for the GridView control:
<asp:GridView ID="YourGridViewControlID" ...... ClientIDMode="Static" runat="server">
3. Javascript Part
And then in your JavaScript file/code:
function TextboxAutoEnableAndDisable(Row) {
// Get current "active" row of the GridView.
var GridView = document.getElementById('YourGridViewControlID');
var currentGridViewRow = GridView.rows[Row + 1];
// Get the two controls of our interest.
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
// If the clicked checkbox is unchecked.
if( rowCheckbox.checked === false) {
// Empty textbox and make it disabled
rowTextBox.value = "";
rowTextBox.disabled = true;
return;
}
// To be here means the row checkbox is checked, therefore make it enabled.
rowTextBox.disabled = false;
}
4. Some Notes for the above implementation
Note that in the JavaScript code, at the line:
var currentGridViewRow = GridView.rows[Row + 1];
the [Row + 1] is important to make this work and should not change.
And finally:
The following lines:
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
The .cells[2] and .cells[0] is maybe different for you, so you have to choose the correct number in the [].
Usually, this will be the column number of your GridView starting counting from 0.
So if your CheckBox was in the first column of the GridView then you need .cells[0].
If your TextBox is in the second column of your GridView then you need .cells[1] (in my case above, TextBox was in the third column of my GridView and therefore, I used .cells[2])
You can use the onclick JavaScript instead of the OncheckedChanged event which is a CheckBox server side event.
<asp:CheckBox ID="CheckBox2" runat="server" onclick="Javascript:JSfunctionName();" />
Edit:
var GridView = document.getElementById('<%=DeptGrid.ClientID %>')
Edit: Upon your request in comment
if (GridView.rows[Row].cell[2].type == "checkbox")
{
if (GridView.rows[Row].cell[2].childNodes[0].checked)
{
GridView.rows[Row].cell[3].childNodes[0].disabled=false;// Enable your control here
}
}
I also found that the statement if (GridView.rows[Row].cell[2].type == "checkbox") results in an error, GridView.rows[Row].cell[2].type is undefined. The code I have running now is as follows:
var grid = document.getElementById('<%=grdResults.ClientID%>');
if (grid.rows.length > 0) {
for (row = 1; row < grid.rows.length; row++) {
if (grid.rows[row].cells[0].childNodes[0].checked) {
// do something here
alert('function for row ' + row);
}
}
You can define your grid like this :
<div>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Calibri"
Font-Size = "12pt" HeaderStyle-BackColor = "LightYellow" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" CssClass="css1 mycss" Text='<%# Eval("Period")%>'
onblur="SetPostingPeriod(this)"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</div>
And your Javascript Function Would be :
<script language="javascript" type="text/javascript">
/* Populating same data to all the textboxes inside grid,
once change of text for one textbox - by using jquery
*/
function SetPostingPeriod(obj) {
var cntNbr = $("#" + obj.id).val();
// var cntNbr = document.getElementById(obj.id).value;
// alert(cntNbr);
//Access Grid element by using name selector
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
});
}
</script>
This Javascript function is called onblur event of the textbox.
When this function is called at the same time it passes a parameter
which is nothing but the textbox id.
Inside javascript function by using the parameter which is the
id of the textbox we are getting the vaue.
Here is the code :
var cntNbr = $("#" + obj.id).val();
Then For each of the "txtPeriod" controls available inside the grid, we need to assign
the value of current "txtPeriod" textbox value to them.
Looping Grid to identify each "txtPeriod" available :
Here is the code :
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
});
Inside this loop we need to assign the "txtPeriod"(current/Modified) value to other
"txtPeriod" textboxes.Before assign its good practice to check is it null or NAN.
Here is the code :
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
Hi here you are having very easy Solution
Suppose your grid is like this :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="64px"
Width="389px" EnableViewState="False">
<Columns>
<asp:TemplateField HeaderText="EmployeeId">
<ItemTemplate>
<asp:Label ID="lblEmployeeId" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FF66FF" ForeColor="#660033" />
</asp:GridView>
and your javascript to find controls inside your grid is
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#btnAddToGrid").click(function () {
var $grid = $('#<%=GridView1.ClientID %>');
var $row = $grid.find('tr:last').clone().appendTo($grid);
var employeeId = $row.find("span[id*='lblEmployeeId']").text();
var firstname = $row.find("span[id*='lblFirstName']").text();
var lastname = $row.find("span[id*='lblLastName']").text();
alert("ID :" + employeeId +"\n" + "Name :" + firstname +" "+ lastname );
});
});
</script>
Find controls inside the grid using java script:
for (var r = 1; r < grid.rows.length; ++r) {
var indexValue = 0; //based on browser. //IE8
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
if (typeof (txtPeriod.value) == "undefined")//IE9
indexValue = 1
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
alert(txtPeriod.value);
}
var x = document.getElementById('<%=grdResults.ClientID%>').querySelectorAll("input");
var i;
var cnt = 0;
for (i = 0; i < x.length; i++) {
if(x[i].type== "checkbox" && x[i].checked)
cnt++;
}
alert("item selected=" + cnt);

Categories

Resources