CheckboxList not getting selected values in javascript - c#

I have checkbox list in asp.net as:
<asp:CheckBoxList ID="chbUserType" RepeatDirection="Horizontal" runat="server">
</asp:CheckBoxList>
I have binded it as:
chbUserType.DataSource = dtRoles;
chbUserType.DataValueField = "idRole";
chbUserType.DataTextField = "Title";
chbUserType.DataBind();
foreach (ListItem li in chbUserType.Items)
{
li.Attributes.Add("JSvalue", li.Value);
}
I want to get its selected values in javascript.
For that i have done as follows:
var userType = "";
var chkBox = document.getElementById('<%=chbUserType.ClientID %>');
var options = chkBox.getElementsByName('input');
var listOfSpans = chkBox.getElementsByTagName('span');
for (var i = 0; i < options.length; i++) {
if (options[i].checked) {
if (i != options.length - 1) {
userType = listOfSpans[i].attributes["JSvalue"].value + ",";
}
else {
userType = listOfSpans[i].attributes["JSvalue"].value;
}
}
}
alert(userType);
I am not getting anything in alert.
Please help me how can i achieve this???
Edit 2 :
Generated HTML
<span jsvalue="2"><input id="MainContent_chbUserType_1" type="checkbox" name="ctl00$MainContent$chbUserType$1" value="2"><label for="MainContent_chbUserType_1">Dispatcher</label></span>

I think if you use the getElementsByTagName on your inputs instead of getElementsByName you'll be fine...
Here is a jsfiddle link that I think represents your problem
var userType = "";
var chkBox = document.getElementById('checkboxlist');
var options = chkBox.getElementsByTagName('input');
var listOfSpans = chkBox.getElementsByTagName('span');
for (var i = 0; i < options.length; i++) {
console.log(options[i].checked);
if (options[i].checked) {
if (i != options.length - 1) {
userType = listOfSpans[i].attributes["JSvalue"].value + ",";
}
else {
userType = listOfSpans[i].attributes["JSvalue"].value;
}
}
}

Related

CheckBoxList In GridView Only Remember The First Option Ticked When New Row Added

I have a grid view with multiple columns which allow user to fill in the data and they are able to add a new row after finishing filling the data. Among the columns, there is a column with CheckBoxList which I allow user to multiple select the option on the CheckBoxList but every time add a new row, only the first option select by the user is remain while other selection is gone. How am I able to let the option selected by the user remain while I add a new row?
private void SetPreviousDataLecturer()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 0; i < dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
LecturerGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
textBoxLName.Text = dataTableCurrent.Rows[i]["LecturerName"].ToString();
textBoxLID.Text = dataTableCurrent.Rows[i]["LecturerID"].ToString();
textBoxLAdd.Text = dataTableCurrent.Rows[i]["LecturerAddress"].ToString();
textBoxLPNumber.Text = dataTableCurrent.Rows[i]["LecturerPNumber"].ToString();
textBoxLEAdd.Text = dataTableCurrent.Rows[i]["LecturerEAddress"].ToString();
checkBoxListLCourse.SelectedValue = dataTableCurrent.Rows[i]["LecturerCourse"].ToString();
textBoxLPassword.Text = dataTableCurrent.Rows[i]["LecturerPassword"].ToString();
rowIndex++;
}
}
}
}
private void AddNewRowToLecturerGV()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
DataRow dataRowCurrent = null;
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 1; i <= dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
dataRowCurrent = dataTableCurrent.NewRow();
dataRowCurrent["RowNumber"] = i + 1;
dataTableCurrent.Rows[i - 1]["LecturerName"] = textBoxLName.Text;
dataTableCurrent.Rows[i - 1]["LecturerID"] = textBoxLID.Text;
dataTableCurrent.Rows[i - 1]["LecturerAddress"] = textBoxLAdd.Text;
dataTableCurrent.Rows[i - 1]["LecturerPNumber"] = textBoxLPNumber.Text;
dataTableCurrent.Rows[i - 1]["LecturerEAddress"] = textBoxLEAdd.Text;
dataTableCurrent.Rows[i - 1]["LecturerCourse"] = checkBoxListLCourse.SelectedValue.ToString();
dataTableCurrent.Rows[i - 1]["LecturerPassword"] = textBoxLPassword.Text;
rowIndex++;
}
dataTableCurrent.Rows.Add(dataRowCurrent);
ViewState["LecturerGridView"] = dataTableCurrent;
LecturerGridView.DataSource = dataTableCurrent;
LecturerGridView.DataBind();
}
}
else
{
Response.Write("ViewState is null.");
}
SetPreviousDataLecturer();
}
You need to maintain state for selected checkbox. On the button click 'Add new row' first get the state of each rows in a DataTable and add a blank row then populate that DataTable.
You need to maintain checkbox's selected item's state also. You can get selected values in a CSV as :
string selectedItems = String.Join(",",
checkBoxListLCourse.Items.OfType<ListItem>().Where(r => r.Selected)
.Select(r => r.Value));
and you can restore as :
string[] items = selectedItems.Split(',');
for (int i = 0; i < checkBoxListLCourse.Items.Count; i++)
{
if (items.Contains(checkBoxListLCourse.Items[i].Value))
{
checkBoxListLCourse.Items[i].Selected = true;
}
}
My answer. This answer has some problem like the checkbox list will automatically scroll to the most top when we tick on anything in the checkbox list.
private void SetPreviousDataLecturer()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 0; i < dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
LecturerGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
textBoxLName.Text = dataTableCurrent.Rows[i]["LecturerName"].ToString();
textBoxLID.Text = dataTableCurrent.Rows[i]["LecturerID"].ToString();
textBoxLAdd.Text = dataTableCurrent.Rows[i]["LecturerAddress"].ToString();
textBoxLPNumber.Text = dataTableCurrent.Rows[i]["LecturerPNumber"].ToString();
textBoxLEAdd.Text = dataTableCurrent.Rows[i]["LecturerEAddress"].ToString();
checkBoxListLCourse.Text = dataTableCurrent.Rows[i]["LecturerCourse"].ToString();
string lecturerCourse = dataTableCurrent.Rows[i]["LecturerCourse"].ToString();
if (!string.IsNullOrEmpty(lecturerCourse))
{
for (int j = 0; j < lecturerCourse.Split(',').Length; j++)
{
checkBoxListLCourse.Items.FindByValue(lecturerCourse.Split(',')[j].ToString()).Selected = true;
}
}
textBoxLPassword.Text = dataTableCurrent.Rows[i]["LecturerPassword"].ToString();
rowIndex++;
}
}
}
}
private void AddNewRowToLecturerGV()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
DataRow dataRowCurrent = null;
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 1; i <= dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
dataRowCurrent = dataTableCurrent.NewRow();
dataRowCurrent["RowNumber"] = i + 1;
dataTableCurrent.Rows[i - 1]["LecturerName"] = textBoxLName.Text;
dataTableCurrent.Rows[i - 1]["LecturerID"] = textBoxLID.Text;
dataTableCurrent.Rows[i - 1]["LecturerAddress"] = textBoxLAdd.Text;
dataTableCurrent.Rows[i - 1]["LecturerPNumber"] = textBoxLPNumber.Text;
dataTableCurrent.Rows[i - 1]["LecturerEAddress"] = textBoxLEAdd.Text;
string lecturerCourse = string.Empty;
foreach (ListItem item in checkBoxListLCourse.Items)
{
if (item.Selected)
{
if (!string.IsNullOrEmpty(lecturerCourse))
{
lecturerCourse += ",";
}
lecturerCourse += item.Value;
}
}
dataTableCurrent.Rows[i - 1]["LecturerCourse"] = lecturerCourse;
dataTableCurrent.Rows[i - 1]["LecturerPassword"] = textBoxLPassword.Text;
rowIndex++;
}
dataTableCurrent.Rows.Add(dataRowCurrent);
ViewState["LecturerGridView"] = dataTableCurrent;
LecturerGridView.DataSource = dataTableCurrent;
LecturerGridView.DataBind();
}
}
else
{
Response.Write("ViewState is null.");
}
SetPreviousDataLecturer();
}

how to stop page from refreshing everytime a checkbox is click

Okay, as simple as possible, I have a checkboxlist that has autopostback set to true and a OnSelectedIndexChanged. However, every time someone clicks a item in the checkbox, the page refreshes. How do I stop this? I've tried using UpdatedPanel(It kind of work).
<asp:CheckBoxList ID="Regions" runat="server" OnSelectedIndexChanged="Regions_SelectedIndexChanged" AutoPostBack="true" DataSourceID="SqlDataSource2" DataTextField="Regions" DataValueField="ID">
</asp:CheckBoxList>
The OnselectedIndexChange displays a div of other checkboxes beside the one checkboxlist.
protected void Regions_SelectedIndexChanged(object sender, EventArgs e)
{
string select = #"Select Facilities from [BulletinBoard].[DMHSAS\290974].[Facilities] ";
int[] ctr = new int[9];
int ctr1 = 0;
int counter = 0;
dFacilities.Style.Add("display", "block");
foreach (ListItem item in Regions.Items)
{
//Response.Write(item.Selected);
if (Regions.SelectedIndex == 0)
{
item.Selected = true;
CheckBoxList1.Visible = true;
counter++;
}
else if (item.Selected)
{
if (select.EndsWith("[Facilities] "))
{
select += "where ";
}
if (select.EndsWith(") "))
{
select += " or ";
}
select += " (Reg_ID = " + Regions.SelectedIndex + ") ";
ctr[ctr1 + 1] = Regions.SelectedIndex;
item.Selected = false;
counter++;
CheckBoxList1.Visible = true;
}
ctr1++;
}
if (counter == 0)
{
CheckBoxList1.Visible = false;
dFacilities.Style.Add("display", "none");
}
ctr1 = 0;
bool all = false;
foreach (int counter1 in ctr)
{
Regions.Items[counter1].Selected = true;
if (Regions.Items[0].Selected == true)
foreach (ListItem item in Regions.Items)
{
if (item.Selected)
{
all = true;
}
else
{
all = false;
break;
}
}
if (all == false)
{
Regions.Items[0].Selected = false;
}
}
You seem to really like the classic .NET postback workflow, but rather than continue down the webforms path of trying to hide postbacks, even though you want them because it makes the logic easier, why not just try sidestepping it just this one time? If, as you say, you want to prevent the page refresh (aka the postback) then there are a few things you can do to prevent it entirely.
At the top of your page:
<style type="text/css">
.hideme
{
display: none;
}
</style>
<script type="text/javascript>
var checkBoxes = document.getElementById("<%= Regions.ClientID %>")
.getElementsByTagName("input");
var cbListIDss = [
"<%= CheckBoxList1.ClientID %>",
"etc"
];
function toggle(i, chkElement)
{
if (chkElement.type == "checkbox") {
if (chkElement.checked) {
var cbElement = document.getElementById(cbListIDss [i]);
cbElement.className = cbElement.className.replace("hideme", "");
break;
}
}
}
for (var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].onClick += toggle(i, checkBoxes[i]);
}
</script>
Edit: Then, in your control, remove these attributes: OnSelectedIndexChanged="Regions_SelectedIndexChanged" AutoPostBack="true"
I didn't add the code for modifying the select variable in your postback method, but that can be done in js as well via a hidden input field.
Alternatively, the reason your update panel is not working is because you have
if (Regions.SelectedIndex == 1)
{
select += " where Reg_ID = 1";
dFacilities.Style.Add("display", "block");
// note the number at the end of this variable
CheckBoxList1.Style.Add("display", "block");
}
if (Regions.SelectedIndex == 2)
{
select += "where Reg_ID = 2";
dFacilities.Style.Add("display", "block");
// note the number at the end of this variable
// All of these are adding display to CheckBoxList1,
// even though it seems like these should be adding
// the display property to CheckBoxList2, 3, etc.
CheckBoxList1.Style.Add("display", "block");
}

CheckBoxList loop not working

I'm trying to select values in a CheckBoxList control based on a data source. I have five items in the CheckBoxList and three items in the data source, but in the loop I only get one item selected.
if (ddlUserId.SelectedIndex != 0)
{
RoleDetails rd;
rd = CatalogAccess.GetSingleUserRole(ddlUserId.SelectedValue.ToString());
for (int i = 0; i < cblRoles.Items.Count; i++)
{
cblRoles.Items.FindByValue(rd.RoleID.ToString()).Selected = true;
}
}
I tried this, but it still selects only one item:
RoleDetails rd;
for (int i = 0; i < cblRoles.Items.Count; i++)
{
rd = CatalogAccess.GetSingleUserRole(ddlUserId.SelectedValue.ToString());
if (cblRoles.Items[i].Value == rd.RoleID.ToString())
cblRoles.Items[i].Selected = true;
}
CheckboxList bind code
cblRoles.DataSource = CatalogAccess.GetRoles();
cblRoles.DataTextField = "RoleDetails";
cblRoles.DataValueField = "RoleId";
cblRoles.DataBind();
When you use for loop you need to use index value (Here it is "i"), like
for (int i = 0; i < cblRoles.Items.Count; i++)
{
if(cblRoles.Items[i].Value == rd.RoleID.ToString())
cblRoles.Items[i].Selected = true;
}
Or you can use foreach as below:
Here i have created looping through items of checkbox list using foreach & item will be made selected id its value will match RoleId .
foreach (ListItem li in cblRoles.Items)
{
if (rd.RoleID.ToString() == li.Value)
{
li.Selected = true;
}
else
{
li.Selected = false;
}
}

how to display validation summary of an asp.net page using Javascript

I have one asp.net form.
In it i have many fields which are required.
I want to display validation summary of all fields at the end of the form.
I have already checked for valid values of input controls.
Now i only want is Summary.
Here is my code for valid data input
<script language="javascript" type="text/javascript">
function userCheck(uName) {
var uName = document.getElementById(uName);
var letters = /^[A-Za-z0-9]+$/;
if (uName.value.match(letters) && uName.value.length != 0) {
uName.style.border = "2px solid #008A2E";
return true;
}
else {
uName.value = uName.value.replace(/[\W]/g, '');
uName.style.border = "2px solid #ff0000";
uName.focus();
return false;
}
}
</script>
This is just one function for username check.
I have many more to deal with.
Is there any way to display summary from all fields at the last when submit button is pressed ?
below solution is not working.
function ddlcheck(ddlclg) {
var clg = document.getElementById(ddlclg.id);
var clgname = document.getElementById('<%= LblCollegeName.ClientID %>');
clgname.style.display = "block";
clgname.innerHTML = "Selected College : " + clg.options[clg.selectedIndex].value;
clg.style.border = "1px solid #008A2E";
if (clg.options[clg.selectedIndex].value == "Select") {
clgname.style.display = "none";
clg.style.border = "1px solid #ff0000";
validationhtml = validationhtml + "<b>*</b> College" + "</br>";
}
}
above code is for dropdownlist.
function select() {
var count = 0;
var chkSelectAll = document.getElementById('<%= ChkSelectAll.ClientID %>');
var chkList = document.getElementById('<%= chk.ClientID %>').getElementsByTagName("input");
for (var i = 0; i < chkList.length; i++) {
if (chkList[i].checked == true) {
count++;
}
}
if (count == chkList.length)
chkSelectAll.checked = true;
else {
chkSelectAll.checked = false;
}
}
above code is for selected check boxes.
create a div ( errorreport) at required location validation summary give it style as you needed
After that
<script language="javascript" type="text/javascript">
var validationhtml="";
function userCheck(uName) {
var uName = document.getElementById(uName);
var letters = /^[A-Za-z0-9]+$/;
if (uName.value.match(letters) && uName.value.length != 0) {
uName.style.border = "2px solid #008A2E";
return true;
} else {
uName.value = uName.value.replace(/[\W]/g, '');
uName.style.border = "2px solid #ff0000";
uName.focus();
validationhtml=validationhtml +"uname is not correct" ;
return false;
}
}
function validationsummary() {
// if using jquery
$(".errorreport").html(validationhtml);
//for javascript
document.getelementbyid("errorreport").innerHTML = validationhtml;
if(validationhtml == "") {
return true;
} else {
return false;
}
}
</script>
and call validationsummary() on submit button click

How to Get Template column Total Throw javascript?

How to get radgrid Template column total throw javascript codebehind.
I solved the problem her is the script
function ValueChanged(sender, args) {
var grid = $find("<%=grd.ClientID %>");//grid id
var totalAmount = 0;
if (grid) {
var MasterTable = grid.get_masterTableView();
var Rows = MasterTable.get_dataItems();
var footer = grid.get_masterTableViewFooter().get_element();
//footer.rows[0].cells[1].innerHTML = 'My Footer Text'; // Set the footer text
var TotalQnty = 0;
var TotalNetAmount = 0;
for (var i = 0; i < Rows.length; i++) {
var row = Rows[i];
var txtIND_QTY = row.findControl("txtgrdIndentQty");//gridcolumns
var txtNetAmount =Number(row.findControl("txtgrdNetamount"));
TotalQnty = TotalQnty + parseFloat(txtIND_QTY.get_value());
TotalNetAmount = TotalNetAmount + txtNetAmount;
}
footer.rows[0].cells[2].innerHTML = "Rs. "+TotalQnty;
footer.rows[0].cells[6].innerHTML = "Rs. "+TotalNetAmount;
alert(TotalQnty);
alert(TotalNetAmount);
}
}

Categories