javascript inside updatepanel - asp.net

im using javascript in asp.net gridview
<script type="text/javascript">
var currentRowId = 0;
function SelectRow()
{
if (event.keyCode == 40)
MarkRow(currentRowId+1);
else if (event.keyCode == 38)
MarkRow(currentRowId-1);
}
function MarkRow(rowId)
{
if (document.getElementById(rowId) == null)
return;
if (document.getElementById(currentRowId) != null )
document.getElementById(currentRowId).style.backgroundColor = '#ffffff';
currentRowId = rowId;
document.getElementById(rowId).style.backgroundColor = '#ff0000';
}
</script>
<script type="text/javascript">
var TargetBaseControl = null;
window.onload = function()
{
try
{
//get target base control.
TargetBaseControl =
document.getElementById('<%= this.GridView1.ClientID %>');
}
catch(err)
{
TargetBaseControl = null;
}
}
function TestCheckBox()
{
if(TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
</script>
button control:
" Width="80px" CssClass="button" />
im using ajax update panel in gridview ...i control postback level but the script is not working inside the updatepanel

In your button_clicked event, you could use this method
ScriptManager.RegisterClientScriptBlock(Control, Type, String, String, Boolean)
More info below
http://msdn.microsoft.com/en-us/library/bb350750.aspx

Related

OnClick and OnClientClick not working together in RadButton

IN RadButton OnClick Event and OnClient Event are not working together. Javascript is not called by OnClient Click in radbutton. I also use RadAjaxSetting.
<script language="javascript" type="text/javascript">
form_dirty = false;
calenderclink = false;
window.onbeforeunload = askUser;
function setSaveEnable() {
document.getElementById('ctl00_ContentPlaceHolder1_btnSave_85').disabled = false;
form_dirty = true;
calenderclink = false;
}
function form_dirty_true() {
document.getElementById('ctl00_ContentPlaceHolder1_btnSave_85').disabled = false;
form_dirty = true;
calenderclink = false;
}
function form_dirty_false() {
form_dirty = false;
calenderclink = false;
Calnederdirty = false;
}
function setSaveEnableforCalender() {
form_dirty = true;
calenderclink = true;
}
function askUser(evt) {
var vtxtSiv = '<%=HndDiscurdMessage.ClientID%>';
var message = document.getElementById(vtxtSiv).value;
if (form_dirty == true && calenderclink == false) {
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
else if (form_dirty == true && calenderclink == true) {
if (document.getElementById('ctl00_ContentPlaceHolder1_rdpWishDate').value != null) {
form_dirty = true;
calenderclink = true;
}
}
}
function ClearAlert() {
var _dvAlert = document.getElementById("<%# dvAlert.ClientID %>");
_dvAlert.attributes[2].value = "display: none;";
form_dirty_true();
}
</script>
<telerik:RadButton ID="btnSave_85" runat="server" CssClass="btnMain btngreen right topRightBtn" OnClientClick="form_dirty_false();" SingleClick="true"
Text="Save" OnClick="btnSave_Click" ></telerik:RadButton>
ONClick is working properly but on clientclick is not working.
Try this out.
<telerik:RadButton ID="btnSave_85" runat="server" CssClass="btnMain btngreen right topRightBtn" OnClientClick="form_dirty_false;" SingleClick="true"
Text="Save" OnClick="btnSave_Click" ></telerik:RadButton>
Then in your javascript have this:
function form_dirty_false(s,a) {
form_dirty_false(); // your original code
}

Resetting textbox text via javascript

function clickButton(e, buttonid)
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt) {
if (evt.keyCode == 13) {
bt.click();
return false;
}
}
}
txtChatMessage.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSendChat.ClientID + "')");
this function is an attribute that is set in code behind file. How do I reset the text in textbox after the button click fires
You can do it like this, by passing the text field from code behind using this, and setting its value to empty string in javascript
In code behind
txtChatMessage.Attributes.Add("onkeypress", "return clickButton(this, event,'" + btnSendChat.ClientID + "')");
In javascript
function clickButton(txt, e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt) {
if (evt.keyCode == 13) {
bt.click();
txt.value = "";
return false;
}
The above code will over write the existing value of text box. To save it for later use we can use hidden field
In html
<asp:hidden id="hdnText" runat="server" >
In javascript
function clickButton(txt, e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt) {
if (evt.keyCode == 13) {
bt.click();
document.getElementById('<%= hdnText.ClientID %>').value = txt.value;
return false;
}
In Code behind
Send text field to javascript function
txtChatMessage.Attributes.Add("onkeypress", "return clickButton(this, event,'" + btnSendChat.ClientID + "')");
Get value of textbox from hidden field
string textBoxValue = hdnText.Value;

check/uncheckbox in gridview tracking

i have a below gridview control with a checkbox on it, so my question is when i hit on save button i able to find the checkbox which have been checked and till here no problem, but the problem started when the user tries to uncheck the checkedbox so how would i track the changes and save it into the db that has been checked. anyhelp?
List<Employee> result = new List<Employee>();
long Id = (long)Session["Id"];
result = Employee.GetEmployeeById(Id);
foreach (GridViewRow row in gv.Rows)
{
CheckBox chkBox = row.FindControl("chkSelected") as CheckBox;
if (c != null)
{
if (result.Count > 0)
{
foreach (Employee item in result)
{
Label Id = row.FindControl("lblId") as Label;
if (Id.Text == item.Id.ToString())
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<script language="javascript" type="text/javascript">
function SelectAll(cb)
{
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
cell.childNodes[j].checked = document.getElementById(cb).checked;
}
}
}
}
}
//--------------------------------------------------------------------------------------------.
function Select(cb)
{
var total = parseInt('<%= this.gv.Rows.Count %>');
var counter=0;
var cbSelectAll=document.getElementById(cb);
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
if(cell.childNodes[j].checked)
counter++;
else
counter--;
}
}
}
}
if(counter==total)
cbSelectAll.checked=true;
else if(counter<total)
cbSelectAll.checked=false;
}
</script>
//----------------------------------------------------------------------------------------
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
CheckBox cbSelect = (CheckBox)e.Row.Cells[0].FindControl("cbSelect");
CheckBox cbSelectAll = (CheckBox)this.gv.HeaderRow.FindControl("cbSelectAll");
cbSelect.Attributes.Add("onclick", "javascript:Select('" + cbSelectAll.ClientID + "')");
cbSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + cbSelectAll.ClientID + "')");
}
}
Yes, store the original value in a hidden field. If always starting with false, you could use JavaScript to set the hidden value to true when the user clicked the checkbox. Using JQuery, you could do:
<asp:TemplateField HeaderText="Select" ItemStyle-CssClass="Checked">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
<asp:HiddenField iD="dh" runat="server" />
</ItemTemplate>
</asp:TemplateField>
$("#<%= Grid.ClientID %>").find(".Checked > :checkbox").each(function() {
$(this).siblings("input[type='hidden']").attr("value", "True");
});
Something like that. On Server side, parse the value and if true, then you know it changed.
HTH.
It may not be the brightest idea, but you can query the database for the current state, and the compare with what you have got from the web page during a postback button click, or something like that. Or you can go with Brians answer.
It is possible to persist a list of objects into the Viewstate and access it in a consequent postback. The only thing is that the object you are trying to persist must be defined as serializable.
Update:
The ViewState approach
I feel this may be suitable for your need, and it requires a bit of linq. You'd need to create a class as follows:
[Serializable()]
public class OptionState
{
//the id of the item
int ID {get;set;}
//state of the checkbox
bool Checked {get;set;}
}
Note the Serializable attribute. This is required for the instance to persist to the viewstate.
Add the list of options to the viewstate:
var lstOptions = (from x in <your_option_store>
select new OptionState{ID = x.ID, Checked = x.Checked}).ToList();
ViewState.Add("options", lstOptions);
Here is a bit of code that should go into your button click:
foreach(GridViewRow row in gvOptions.Rows)
{
//not writing the bit of code
//which gets the ID and the
//state of checkbox of
//the gridview row being processed
OptionState currentState = GetOptionStateObjectFromRow(row);
List<OptionState> lstStates = (List<OptionState>) ViewState["options"];
OptionState originalState = lstStates.FirstOrDefault(x => x.ID == currentState.ID);
if(currentState.Checked != originalState.Checked)
{
//the appropriate db call needs to be done here.
}
}

asp.net button click event not working with firefox

Following is the code that i am using. It work in IE but the button click event is not generated properly in firefox:
function trapEnter(btn,hdn, event) {
var key;
var isIE = true;
debugger;
if (window.event) {
key = window.event.keyCode; //IE
isIE = true;
}
else {
key = event.which; //firefox
isIE = false;
}
if (key == 13) {
var btn = document.getElementById(btn);
if (btn != null) { //If we find the button click it
document.getElementById(hdn).value = '1'
btn.click();
key = 0;
}
}
}
I think your function has the wrong parameters. Try this:
function trapEnter(e) {
e = e || window.event || event;
var code = e.charCode || e.keyCode || e.which;
if (code == 13) {
var btn = document.getElementById('<%= YourButtonID.ClientID %>');
if (btn != null) { //If we find the button click it
document.getElementById(hdn).value = '1';
btn.click();
key = 0;
}
}
}

How do i maintain the state of my Html Controls on postback with JQuery and JSON?

I have a form with a collection of Html and ASP Server Controls. Im using JSON to preload some drop-down lists.
I want to maintain the states of these drop-down lists on postback. Im quite new to JSON, can anyone help?
If you can use HTML select element instead. Thus, you can get the selected value of select element on the server and register an hidden field to maintain the value. While you are loading the items so you can check the registered hidden field to retrieve the previous selected value.
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script type="text/javascript">
var sv = document.getElementById("SelectedValue");
var v = (sv != null && sv.value != "" ? sv.value : null);
var o = document.getElementById("DropDownList1");
for (var i = 0; i < 10; i++) {
var item = document.createElement("option");
item.innerHTML = "item" + i;
item.setAttribute("value", "item" + i);
if (("item" + i) == v)
item.setAttribute("selected", "selected");
o.appendChild(item);
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
firstly, you should create an HTTPHandler to generate the JSON and get it using getJSON method from jQuery. Lastly, you have to get the selected value on the Load event of the page and maintain the value to a HiddenField for the next time. The following code demonstares it.
public class JsonGenerator : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
JavaScriptSerializer ser = new JavaScriptSerializer();
context.Response.Write(ser.Serialize(new object[]
{
new { Text = "Item1", Value = 1 },
new { Text = "Item2", Value = 2 } ,
new { Text = "Item3", Value = 3 }
}));
}
public bool IsReusable
{
get
{
return false;
}
}
}
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("JsonGenerator.ashx",
null,
function(r) {
var ddl = $("#DropDownList1"), hf = $("#SelectedValue");
$.each(r, function(k, v) {
ddl.append("<option value='" + v.Value + "'>" + v.Text + "</option>");
});
if (hf.length > 0)
ddl.children("[value='" + hf.val() + "']").attr("selected", "selected");
});
});
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
Don't let the browser do the post, do it yourself with jQuery. On the callback replace a results div with the returned html.
Assuming you've marked your form with class="ajaxform" and your results div with id="results" then something like this (not fully tested)...
// Submit form.ajaxform
// Get the returned html, and get the contents of #results and
// put it into this page into #results
var submit = function() {
$.ajax({
type: "POST",
data: $("form.ajaxform").serialize(),
success: function(data, textStatus) {
$("#results").replaceWith($("#results", $(data)));
}
});
};
$("form.ajaxform input[type=submit]").click(submit);
// I think you'll need this as well to make sure the form doesn't submit via the browser
$("form.ajaxform").submit(function () { return false; });

Resources