I want to to get listbox id inside the listview in javascript.
This is my Javascript:
<script>
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(
function (sender, e) {
var control = $find('<%= results.ClientID %>');
if (e.get_postBackElement().id =="<%=this.results.ClientID%>") {
$get("divvv").style.display = "none";
}
else {
$get("divvv").style.display = "block";
}
});
</script>
results is my listbox id but it is in the listview so that i couldn't get the listbox it directly as specified above.It shows Error.
Please hel me.Thanks in advance
i havent tested but you can try this
function (sender, e) {
var control = $find('<%= ((ListBox)MyListView.FindControl("myListBox")).ClientID %>');
if (e.get_postBackElement().id =='<%= ((ListBox)MyListView.FindControl("myListBox")).ClientID %>') {
$get("divvv").style.display = "none";
}
else {
$get("divvv").style.display = "block";
}
Related
I have a button in my page which is used to save data of gridview which is dynamically populated. Before saving I want to check some condition. The javascript function is as follows:
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("This will completely delete the project. Are you sure?")) {
confirm_value.value = "Yes";
}
else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" onClientClick="Confirm()"></button>
The code behind is as follows:
protected void lnkBtn_Click(object sender, EventArgs e)
{
string str=gdView.HeaderRow.Cells[8].Text;
System.Web.UI.WebControls.TextBox txtID = (System.Web.UI.WebControls.TextBox)gdView.Rows[0].Cells[8].FindControl(str);
if (txtID.Text != "")
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
MyAlert("Yes clicked");
}
else
{
MyAlert("No clicked");
}
}
else
{
MyAlert("No Text found.");
}
}
Now the problem is since I have the function Confirm() in the onClientClick event, the confirm dialog appears the moment the user clicks the button, instead it should appear only when a string is found in txtID.
I tried to modify the code by removing the onClientClick event as follows:
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" ></button>
protected void lnkBtn_Click(object sender, EventArgs e)
{
string str=gdView.HeaderRow.Cells[8].Text;
System.Web.UI.WebControls.TextBox txtID = (System.Web.UI.WebControls.TextBox)gdView.Rows[0].Cells[8].FindControl(str);
if (txtID.Text != "")
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "confirm", "Confirm();", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
MyAlert("Yes clicked");
}
else
if (confirmValue == "No")
{
MyAlert("No clicked");
}
}
}
Here also it is not working properly. The confirmValue is getting the value but using it only during the subsequent click of the button. It is not passing value stored during the present click event instead the previously stored value is passed to if block. Please help to find what should I do get it right.
Thanks.
I have a Asp.Net c# application in which, having Logout Button on mAsterpage.
I am trying to alert confirmation window on click of LogOut. If i choose Yes, then I will redirect it into Log-in Page.
So I have tried below. OnClient Click I called below JavaScript Function.
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
On Button Click I have wriiten Below code.
protected void ImgbtnLogOut_Click(object sender, ImageClickEventArgs e)
{
try
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Session.Clear();
Session.Abandon();
Response.Redirect(ConfigurationManager.AppSettings["LogoutURL"].ToString());
//Server.Transfer(ConfigurationManager.AppSettings["LogoutURL"].ToString());
}
else
{
//Do Nothing
}
}
catch (Exception ex)
{
}
finally
{
}
}
I am getting an error Unable to evaluate Expression, The code is Optimized....error in below line. And Page is not being redirected to required page.
Response.Redirect(ConfigurationManager.AppSettings["LogoutURL"].ToString());
can anyone please suggest, how can i achieve that.
This confirm box help you to get correct response with having Ajax.
java script code for geting confirm value.
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to proceed continue ?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
On C# Code for geting exect data.
string confirmValue = Request.Form["confirm_value"];
string[] Value_Confirm = confirmValue.Split(',');
if (Value_Confirm[Value_Confirm.Length-1] == "Yes")
{}
or check here : http://www.codeproject.com/Answers/1070495/Ask-yes-no-cancel-window-in-csharp#answer6
can you help me with this simple problem of mine in asp.net,
I have 3 textboxes; Txt1 Txt2 txt3
If txt1 is not empty, txt2 and txt3 requiredvalidator should be enabled.
if txt1 is empty, txt2 and txt3 requiredvalidator should not be enabled,
Here's the requirement, once txt1 has a value, txt2 and txt3 should be a required field.
can someone help me with this??
Thank you so much.
Can somebody check this code for me? THANK YOU so much
<script type="text/javascript" language="javascript">
function FatherClientValidate(oSrc, args) {
var textBox = document.getElementById('<%=FatherName.ClientID%>');
if (textBox.value != '') {
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
document.getElementById(ctrlid).style.backgroundColor = "#ff0000";
args.IsValid = true;
}
else {
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
document.getElementById(ctrlid).style.backgroundColor = "White";
args.IsValid = false;
}
}
</script>
You can use CustomValidators for Txt2 txt3 , On server validation event of custom validator you can check like below
void ServerValidation (object source, ServerValidateEventArgs args)
{
if (!string.IsNullOrEmpty(Txt1.Text))
args.IsValid = !string.IsNullOrEmpty(args.Value);
}
In client side validation
<script language="javascript">
function ClientValidate(source, arguments)
{
var textBox = document.getElementById('<%=Txt1.ClientID%>');
if (textBox.value !== "" ){
arguments.IsValid = (args.value !== "");
} else {
arguments.IsValid = false;
}
}
</script>
I use checkbox control in gridview i want to show confirm before checkboxchanged event.
Confirm box is asking question but not postback it, doing nothing...
// CS
TemplateField field = new TemplateField(){
HeaderText = "AKTIF",
ItemTemplate = new AddTemplateToGridView("AKTIF")
};
field.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
field.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
field.ItemStyle.Width = Unit.Pixel(40);
newXGrid.Columns.Add(field);
// ITEMPLATE
public class AddTemplateToGridView : ITemplate
{
String columnName;
public AddTemplateToGridView(String colname)
{
columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
if (columnName == "AKTIF")
{
CheckBox chk = new CheckBox() { ID="chkAktif", AutoPostBack=true };
chk.Attributes.Add("onclick","return confirm('Are you sure ?')");
chk.CheckedChanged += new EventHandler(l_CheckedChanged);
container.Controls.Add(chk);
}
}
void l_CheckedChanged(object sender, EventArgs e)
{
...
}
}
// My checkbox on page
<input id="ctl00_MainContent_ctl11_ctl02_chkAktif" type="checkbox" name="ctl00$MainContent$ctl11$ctl02$chkAktif" onclick="return confirm('Are you sure ?');setTimeout('__doPostBack(\'ctl00$MainContent$ctl11$ctl02$chkAktif\',\'\')', 0)">
Change this:
chk.Attributes.Add("onclick","return confirm('Are you sure ?')");
to this:
chk.Attributes.Add("onclick","if (!confirm('Are you sure ?')) return false;");
Set AutoPostBack="true" for the Checkbox to trigger the postback on click.
You are preventing javascript to execute setTimeout() by using return with confirm dialog.
Try this:
if(confirm('Are you sure?'))
setTimeout('__doPostBack(\'ctl00$MainContent$ctl11$ctl02$chkAktif\',\'\')', 0);
else
return false;
I am trying to return in a string the selected items from a dynamically bound checkbox list control with no luck. I'm hoping someone can help. In my code behind file I am conencting to a class called users and building a datatable. I then bind the data table to the cblist control
private void populateUserList() //called on page load
{
SubmitOptions mySubmission = new SubmitOptions(juris, rptType, tmplName);
if (mySubmission.Users.Count == 0)
{
lbl_juris.Visible = false;
cb_selectUser.Visible = false;
lbl_AlertMsg.Visible = true;
btnSelect.Visible = false;
lbl_AlertMsg.Text = "No supervisors listed for jursidiction: " + juris.ToString();
}
else
{
dt.Columns.Add("Users");
for (int i = 0; i < mySubmission.Users.Count(); i++)
{
DataRow dr = dt.NewRow();
dr["Users"] = mySubmission.Users[i];
dt.Rows.Add(dr);
}
cb_selectUser.DataSource = dt;
cb_selectUser.DataBind();
}
}
Within the main aspx file I have the control defined as:
<asp:CheckBoxList ID="cb_selectUser"
Width="400px"
Height="100%"
AutoPostBack="false"
runat="server"
CellPadding="2"
CellSpacing="5"
DataTextField="Users"
DataValueField="Users"
>
</asp:CheckBoxList>
I have tried the following code where i itterate through the list but this only seems to work if I hard code values into the Checkboxt list as listitems.
protected void btn_returnUserList(object sender, System.Web.UI.ImageClickEventArgs e)
{
for (int i = 0; i < cb_selectUser.Items.Count; i++)
{
if (cb_selectUser.Items[i].Selected)
{
selectedUsers += cb_selectUser.Items[i].Text;
}
}
The list populates fine and all I want to do is return in a string all selected users from the checkbox list control.
As I said if I hard code the item values into the control the above code works and I can see the selected items in the string however removing the itemslist tags and switching over to a binding nothign happens. The above method counts the entire number of returns but nothing selected is ever returned.
Any tips or suggestions as to what I am missing would be greatly appreciated.
here is complete code of page working exactly as you want it. just add a CheckboxList to form name it to list1, add a button name it to btn and add a label and name it lbl.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var dt = new DataTable();
dt.Columns.Add("Users");
const string str = "User {0}";
for(var i=1;i<=10;i++)
{
//var r = dt.NewRow();
//r.ItemArray=new object[]{string.Format(str,i)};
dt.Rows.Add(new object[] {string.Format(str, i)});
}
list1.DataSource = dt;
list1.DataTextField = "Users";
list1.DataBind();
}
}
protected void btn_Click(object sender, EventArgs e)
{
var s = list1.Items.Cast<ListItem>()
.Where(item => item.Selected)
.Aggregate("", (current, item) => current + (item.Text + ", "));
lbl.Text = s.TrimEnd(new[] {',', ' '});
}
Are you sure populateUserList() is only being called once? (i.e. not on postback as well). If it gets called twice the selected items collection will be blank.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
populateUserList();
}
}
1- Download Jquery.json.js and add it to your view as refrence:
<script src="../../Scripts/jquery.json.js" type="text/javascript"></script>
2- I've added a ".cssMyClass" to all checkboxlist items so I grab the values by their css class:
<script type="text/javascript" >
$(document).ready(function () {
$("#btnSubmit").click(sendValues);
});
function populateValues()
{
var data = new Array();
$('.myCssClas').each(function () {
if ($(this).attr('checked')) {
var x = $(this).attr("value");
data.push(x);
}
});
return data;
}
function sendValues() {
var data = populateValues();
$.ajax({
type: 'POST',
url: '#Url.Content("~/Home/Save")',
data: $.json.encode(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () { alert("1"); }
});
}
</script>
3- As you can see I've added all selected values to an Array and I've passed it to "Save" action of "Home" controller by ajax
4- in Controller you can receive the values by adding an array as argument:
[HttpPost]
public ActionResult Save(int[] val)
{
I've searched too much but apparently this is the only solution. Please let me know if you find a better solution for it.
string skills="";
for(int i=0;i<chkboxlist.Items.Count;i++)
{
if(chkboxlist.Items[i].Selected)
{
skills=skills+chkboxlist.Items[i].Text+",";
}
}
skills = skills.Remove(skills.Length-1);
lblResult.Text = skills.ToString();
You need to ensure your checkboxlist has databound before trying to retrieve values from it.
Can you use the sender to retrieve your selected items and see if you get the same result?
protected void btn_returnUserList(object sender, System.Web.UI.ImageClickEventArgs e)
{
CheckBoxList cbl = sender as CheckBoxList;
if (sender == null) {
throw new Exception("Sender is not a CheckBoxList");
}
for (int i = 0; i < cbl.Items.Count; i++)
{
if (cbl.Items[i].Selected)
{
// Also, set a breakpoint here... are you hitting this line?
selectedUsers += cbl.Items[i].Text;
}
}
Also, test to see if you're getting into the block for selected items... are they registering as selected, but not getting the text back? Or do the items not show up as selected in the first place?
Try out this one:-
foreach (ListItem li in cb_selectUser.Items)
{
//Your Code
}
I had same problem. You have to bind the CheckBoxList as follows:
if(!IsPostBack)
{
//Bind your checkboxlist
}