Hello, is it possible to get the current rowindex of a gridview using jQuery?
Bit of background:
I delete rows from a gridview using a server side link button in a template field like so:
<asp:LinkButton CausesValidation="false" CommandName="Delete" ID="lnkDelete"
OnClientClick="javascript: return(confirm('Delete item?'));" runat="server" Text="Delete" />
Which prompts the user to confirm or cancel the deletion. If the user clicks OK, it then calls this method on the codebehind:
protected void GridViewRowDeleting(object sender, GridViewDeleteEventArgs e)
{
this.gridview_uploads.EditIndex = -1;
if (!this.UploadsList.Count.Equals(0))
{
DocumentUpload upload = this.UploadsList[e.RowIndex];
if (upload != null)
{
this.UploadsList.RemoveAt(e.RowIndex);
this.BindInputGridview();
}
}
}
But the javascript confirm (Delete item?) looks a bit naff.
I'd much prefer to use something like JQuery's dialog, but if I do, I have no idea how to grab the rowindex using this approach (I can figure out how to call the server code).
Any ideas?
Sorry if this has already been asked - I did a trawl of SO and Googled it but couldn't find anything useful.
If the LinkButton is the only LinkButton/Anchor within the GridView, then you should be able to do something like
$('#GridView1 a').click(function(){
return confirm("Delete Item");
});
edit: change the #GridView1 to the .net ID of the control.
vb
<%=(me.GridView1.ClientID)%>
c#
<%=(this.GridView1.ClientID)%>
Reply to adrianos
If you look into the jQuery UI Dialog, this has a nice Modal Confirmation box.
In a similar way to the above code, but replacing the confirm function, you could have:
<script type="text/javascript">
$().ready(function(){
$( "#dialog" ).dialog( "destroy" );
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
autoOpen: false;
buttons: {
"Delete item": function() {
$( this ).dialog( "close" );
// Put in your return true/false here to activate button
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
$('#GridView1 a').click(function(){
$('#dialog-confirm').dialog("open");
return false;
});
)};
</script>
I figured out how to do this using the __doPostBack method (in Javascript)
>>> In the aspx:
Hidden field:
<asp:HiddenField ID="hidden_gridRowIndex" runat="server" />
In a script tag:
$(document).ready
(
function () {
$("#div_dialog_confirmUploadDelete").dialog({
autoOpen: false
, title: "Delete upload"
, buttons: {
"OK": function () {
__doPostBack('GridViewRowDelete', $("#<%# hidden_gridRowIndex.ClientID %>").val());
$(this).dialog('close');
}
, "Cancel": function () { $(this).dialog('close'); }
}
});
});
function deleteConfirm(index) {
$("#<%# hidden_gridRowIndex.ClientID %>").val(index)
$("#div_dialog_confirmUploadDelete").dialog('open');
}
On the gridview:
<asp:TemplateField>
<ItemTemplate>
<a href="javascript: void(0);" onclick='javascript:return deleteConfirm(<%# Container.DataItemIndex %>);'>Delete</a>
</ItemTemplate>
</asp:TemplateField>
>>> In the codebehind
On Page_Load:
if (Request["__EVENTTARGET"] != null)
{
switch (Request["__EVENTTARGET"])
{
case "GridViewRowDelete":
if (Request["__EVENTARGUMENT"] != null)
{
int index = -1;
if (int.TryParse(Request["__EVENTARGUMENT"], out index))
{
this.GridViewRowDelete(index);
}
}
break;
}
}
New method called by the page_load:
protected void GridViewRowDelete(int rowIndex)
{
this.gridview_uploads.EditIndex = -1;
if (!this.UploadsList.Count.Equals(0))
{
DocumentUpload upload = this.UploadsList[rowIndex];
if (upload != null)
{
this.UploadsList.RemoveAt(rowIndex);
this.BindInputGridview();
}
}
}
Thinking about it, I could have probably made the asp:HiddenField a regular html hidden input control as the server side never needs to see it.
It feels a bit ropey so feel free to throw stones at me / suggest improvements.
Add a custom attribute to your grid and set value on binding event
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="#" test='<%# Container.DataItemIndex %>'>content</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Using .net clientId get the custom attribute value.
$(document).ready(function () {
$('#<%=(this.GridView1.ClientID)%> a').click(function () {
return alert("Last Name : " + this.getAttribute("test") );
})
}
);
Related
I realise this question has been asked but none of the answers worked for my project.
I have a button that when clicked calls an API, so there is a 1 second delay.
I have tried several things nothing works.
btnSave.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
Even that does nothing.
Prevent Double Click .Please add below code in your aspx page.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) { var oControl = args.get_postBackElement(); oControl.disabled = true; }
</script>
This solution is simple and effective. On your button include this code:
OnClientClick="return CheckDouble();"
And wherever you want your JavaScript - e.g. At the bottom of your page:
<script type="text/javascript">
var submit = 0;
function CheckDouble() {
if (++submit > 1) {
alert('This sometimes takes a few seconds - please be patient.');
return false;
}
}
</script>
Most of the above suggestions failed to work for me. The one that did work was the following by tezzo:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
Simpler still, rather than using the above in the code-behind, just use the following:
<asp:Button ID="btnSave" runat="server" Text="Save"
UseSubmitBehavior="false"
OnClientClick="this.disabled='true';"
</asp:button>
UseSubmitBehavior="false" is the key.
You can prevent double-clicking using this code:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
So you can use btnSave_Click to call your API.
Usually I have a lot of Validators in my Page: setting Validator.SetFocusOnError = True I can run this code to reenable save button if a validation failed.
Me.YourControl.Attributes.Add("onfocus", Me.btnSave.ClientID & ".removeAttribute('disabled');")
This is the one I found works in all cases.
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Clicked" />
<asp:Button ID="Button2" runat="server" Text="Button2" />
</form>
Now here’s the short JavaScript snippet that will disable the button as soon as it is clicked so that when PostBack occurs the button cannot be clicked again.
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
The above script disables the ASP.Net Button as soon as the page is ready to do a PostBack or the ASP.Net form is submitted.
But in cases you might want to disable all Buttons and Submit Buttons on the page hence for such cases I have created another function which disables all Buttons and Submit buttons whenever there’s a PostBack or form submission
<script type = "text/javascript">
function DisableButtons() {
var inputs = document.getElementsByTagName("INPUT");
for (var i in inputs) {
if (inputs[i].type == "button" || inputs[i].type == "submit") {
inputs[i].disabled = true;
}
}
}
window.onbeforeunload = DisableButtons;
</script>
Prevent Double Click .Please add below code in your aspx page
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
At first my solution is like this:
<script>
function disableButton(btn) {
setTimeout(function () { btn.disabled = true; }, 20);
return true;
}
</script>
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" OnClientClick="return disableButton(this);" />
Without setTimeout the button will be immediately disabled and then the OnClick event will not be fired. The drawback of this approach is that the Save button will not be accessible anymore if some validation fails or some error happens.
So I don't think disable the button is a good solution, and come up with another solution:
function disableButton(btn) {
if (btn.hasclicked) return false;
btn.hasclicked = 1;
btn.onmouseenter = function () { this.hasclicked = 0; };
return true;
}
But my colleague points out that if the post processing is very slow, before it is finished, the user is still able to perform the double postback by leave-enter-click the button. So I figured out another two solutions:
Run the validation from client before submitting the form. But if your page contains multiple ValidationGroup, it is said that the following Page_ClientValidate() should be called multiple times with a passed-in ValidationGroup parameter: e.g. Page_ClientValidate("group1"):
function disableButton(btn) {
if (Page_ClientValidate) {
Page_ClientValidate();
if (!Page_IsValid) {
btn.setAttribute("btnClicked", "n");
return true;
}
}
if (btn.getAttribute("btnClicked") == "y") {
return false;
} else {
btn.setAttribute("btnClicked", "y");
return true;
}
}
As the ASP.NET has only one form in a page (not ASP.NET MVC), we can also let the onsubmit client event of the form to intercept the double click:
function disableButton(btn) {
$("form").submit(function () {
if (btn.getAttribute("btnClicked") == "y")
return false;
else
btn.setAttribute("btnClicked", "y");
return true;
});}
I'll ask QA to test those two approaches(Post edit: QA has proved that it is very dangerous to use this approach. Please refer to my following comments for details).
Try this way, it's a working solution:
For all browsers including Opera Mobile browser which doesn't support js, means your form will not be blocked in that type of browsers.
Add this in Page_load() method:
BtnID.Attributes.Add("onclick", "if(typeof (Page_ClientValidate) === 'function' && !Page_ClientValidate()){return false;} this.disabled = true;this.value = 'Working...';" + ClientScript.GetPostBackEventReference(BtnID, null) + ";");
I have a LinkButton that I need to perform a click on to cause a postback. The actual link target is:
javascript:__doPostBack('ctl00$c1$btnRefreshGrid','');
Clicking the link does perform the postback, as verified by a breakpoint in the code-behind. Also pasting javascript:__doPostBack('ctl00$c1$btnRefreshGrid','') in the address bar of the browser works with the same effect.
I've tried the following with no effect at all:
__doPostBack('ctl00$c1$btnRefreshGrid','');
$('#ctl00$c1$btnRefreshGrid').click();
$('#ctl00$c1$btnRefreshGrid').trigger('click');
eval($('#ctl00$c1$btnRefreshGrid').attr("href"));
I've tried using both <%= btnRefreshGrid.UniqueID %> and <%= btnRefreshGrid.ClientID %> to generate the selector.
You were close, this works in Firefox:
function clickMyButton() {
javascript:__doPostBack('<%= MYBUTTONID.UniqueID %>','')
};
the following works for the following anchor (originally asp:LinkButton in server side) inside li
<li>
<a id="ctl00_ContentPlaceHolder1_ChangeNumberItemGrd_ctl01_FindByID" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$ChangeNumberItemGrd$ctl01$FindByID','')">287573</a>
</li>
because i do not have the name i must generate it from it
$(".msglist li").on("click", function () {
var postbackArg = $(this).find("a").prop("id").replace(/_/g,"$");
__doPostBack(postbackArg, '');
});
$("#<%= btnRefreshGrid.ClientID %>").click();
Should work...
Hope it helps!!!
In firebug you can get the correct name and link action of the link button:
<a id="MainContent_ctl00_Submit_Button" href="javascript:__doPostBack('ctl00$MainContent$ctl00$Submit_Button','')"></a>
var Eventtarget = $("#btnSave").attr("name");
__doPostBack(Eventtarget, "");
ASP.NET:
<asp:LinkButton ID="btnDelete" runat="server" CssClass="btn-u btn-u-xs btn-u-red"
OnClientClick="return get_confirm(this,event);"> <i class='fa fa-trash-o'> Delete </i> </asp:LinkButton>
JavaScript:
function get_confirm(obj, e) {
e.preventDefault()
var postbackArg = obj.href.replace("javascript:__doPostBack('", "").replace("','')", "");
$.confirm({
title: 'Confirm',
content: 'Are you sure to delete this item?',
closeIcon: true,
buttons: {
confirm: {
text: 'Ok',
btnClass: 'btn-red',
action: function () {
__doPostBack(postbackArg, '');
}
},
cancel: {
text: 'Cancel',
action: function () {
}
}
}
});
}
I need to show the confirm box "Are you sure You Want To continue?" If "Yes" I need the ASP.NET textbox value to be cleared out. Otherwise it should not be cleared.
function doConfirm(){
if (confirm("Are you sure you want to continue?")){
var mytxtbox = document.getElementById('<% =myAspTextBox.ClientID %>');
mytxtbox.value = '';
}
}
Note the myAspTextBox refers to the name of the asp:textbox controls ID property
<asp:textbox ID="myAspTextBox" runat="server" OnClientClick="javascript:doConfirm();"
Hope this helps
In your asp textbox tag add this:
OnClientClick="javascript:testDeleteValue();"
...
And add this script:
<script>
function testDeleteValue()
{
if (window.confirm('Are you sure You Want To continue?'))
document.getElementById("<%=<th id of your textbox>.ClientID%>").value = '';
}
</script>
If you want this to happen on click of your radio box, put it in this tag and just replace onclientclick with onclick.
<input type='radio' onclick='testDeleteValue()'/>
If you download the AjaxControlToolkit you can use the ConfirmButtonExtender to display a simple confirmation box to a user after a button is clicked to proceed with the action or cancel
You can see here for an example and here for a tutorial on how to implement this
Okay I just noticed the bit about radio buttons, in any case the AjaxControlToolkit is a good place to start if you want to implement JavaScript solutions in .Net projects
if this is your textbox markup:
<asp:textbox id="txtInput" runat="server" />
and then this is the button that will trigger the confirm:
<asp:button id="btnSumbit" runat="server" onclientclick="return clearOnConfirm();" text="Submit" />
then you'll need the following javascript:
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
return true;
} else {
return false;
}
}
</script>
If all you want to do is to clear the textbox but always continue with the postback then you don't ever need to return false as above but always return true as below. In this scenario you should rethink the message you display to the user.
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
}
return true;
}
</script>
function stopTimer() {
if (window.confirm('Are you sure You Want To continue?')) {
$find('Timer1')._stopTimer()
return true;
}
else {
return false;
}
<asp:Button ID="Btn_Finish" runat="server" Text="Finish" Width="113px" OnClick="Btn_Finish_Click" OnClientClick="return stopTimer();" Height="35px"
protected void Btn_Finish_Click(object sender, EventArgs e)
{
Timer1.Enabled = false;
// if any functions to be done eg: function1();
Response.Redirect("~/Default2.aspx");
}
There is also a timer stop doing in the function. The confirmation box if press "Ok" timer stops and also its redirected to new page "Default2.aspx"
else if chosen cancel then nothing happens.
In button click event how can I check all check boxes in gridview?
I dont need header checkbox.
Please provide your knowledge
awaiting your response....
Thanks
<input id="btncheckall" type="button" value="select all" />
add click event handler to button above (with jQuery)
<script type="text/javascript">
$(function(){
$("#btncheckall").click(function(){
$("#gridview input:checkbox").attr("checked","checked");
});
});
</script>
or you can use checkbox.
this is a checkbox outside gridview
<input id="checkall" type="checkbox" />
add change event handler to checkbox above (with jQuery)
<script type="text/javascript">
$(function(){
$("#checkall").change(function(){
$("#gridview input:checkbox").val( $(this).val() );
});
});
</script>
Assign a class to all your grid row check boxes and use the below script to get them all.
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
And you've to call it this way:
var messages = getElementsByClass("childbox");
Assign a class childbox to grid row child box.
document.getElementById("parentbox").onclick = function() {
for(var index=0; index < messages.length; index++) {
// prompt the content of the div
//message[index].checked = (message[index].checked) ? false : true;
}
}
you'll assign the parentbox class to the parent checkbox which is in grid header.
You don't need to define them - parentbox and childbox.
C#
Let's say you have a check all button
<asp:CheckBox ID="chkSelectAll" runat="server" Text="SelectAll"
AutoPostBack="true" OnCheckedChanged="chkSelectAll_CheckedChanged" />
and in that click event you would do something like:
protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk; //assuming your gridview id=GridView1
foreach (GridViewRow rowItem in GridView1.Rows)
{
chk = (CheckBox)(rowItem.Cells[0].FindControl("chk1"));
chk.Checked =((CheckBox)sender).Checked;
}
}
javascript approach:
<script language="javascript">
function SelectAllCheckboxes(spanChk){
// Added as ASPX uses SPAN for checkbox
var oItem = spanChk.children;
var theBox= (spanChk.type=="checkbox") ?
spanChk : spanChk.children.item[0];
xState=theBox.checked;
elm=theBox.form.elements;
for(i=0;i<elm.length;i++)
if(elm[i].type=="checkbox" &&
elm[i].id!=theBox.id)
{
//elm[i].click();
if(elm[i].checked!=xState)
elm[i].click();
//elm[i].checked=xState;
}
}
</script>
Checkbox field as so:
<asp:CheckBox ID="chkAll" runat="server" Text="SelectAll"
onclick="javascript:SelectAllCheckboxes(this);" />
Hai Dominic,
If you want javascript look at this
https://web.archive.org/web/20210304130956/https://www.4guysfromrolla.com/articles/052406-1.aspx#postadlink
or
Check box in gridview with button
Jquery can make this easier. Hook into the external boxes onslected event, and inside there iterate the grid boxes selecting them all.
This is a great example of the evils of asp.net and how it's use by new developers really cripples them into thinking that all processing and interaction takes place server side, and all sorts of crazy hacks take place to maintain this illusion. It's backwards and insane.
Try this:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate><asp:CheckBox ID="SelectUnSelectAllCheckBox" runat="server" /></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="SelectCheckBox" runat="server" /></ItemTemplate>
</asp:TemplateField>
<!-- Other columns are omitted -->
</Columns>
</asp:GridView>
<script type="text/javascript">
$(document).ready(function(e) {
$("input[id$='SelectUnSelectAllCheckBox']").change(function() {
$("input[id$='SelectCheckBox']").attr("checked", this.checked);
});
});
</script>
If you're using jquery you could use the $('input:checkbox') selector so something like
<script type="text/javascript">
$(function() {
$('#NameOfButtonToSelectAll').click( function() {
$('input:checkbox').each( function() {
this.checked = !this.checked;
});
});
});
</script>
Kindly check it out and let me know when you got it worked.
Using Javascript :
http://wiki.asp.net/page.aspx/281/check-uncheck-checkboxes-in-gridview-using-javascript/
Using Serverside Script: (VB.Net)
https://web.archive.org/web/20211020145756/https://aspnet.4guysfromrolla.com/articles/052406-1.aspx
Using jQuery:
$('#SelectAll').click(function(){
var checked = $(this).is(':checked');
var allCheckboxes = $('table input:checkbox');
if(checked)
allCheckboxes.attr('checked','checked');
else
allCheckboxes.removeAttr('checked');
});
You probably want to change the selectors, assuming you have a class for your grid and checkbox.
I'm trying to use Telerik's RadSpell to spellcheck some text when the user submits it.
The way this is supposed to work is by stopping the postback, triggering the spellcheck through javascript, then in the spellcheckfinished event manually starting the real postback. The problem is that in the last step the Clicked event isn't firing for the button and the server side event handler never gets called.
Here is the relevant .aspx code:
<script type="text/javascript" language="javascript">
var spellCheckFinished = false;
var btnClicked;
function doSpellCheckStuff(btnTrigger)
{
btnClicked = btnTrigger;
var spell = GetRadSpell('<%= rsMessage.ClientID %>');
// spell.add_clientCheckFinished(checkFinished);
spell.startSpellCheck();
return false;
}
function checkFinished(sender, args)
{
args.SuppressCompleteMessage = true;
setTimeout('MySubmit();', 100);
}
function MySubmit()
{
WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions(btnClicked.id, '', true, '', '', false, true)
);
}
</script>
<tr>
<td>
<asp:Button ID="btnSubmit" OnClientClick="return doSpellCheckStuff(this);" Text="Submit"
OnClick="btnSubmit_Click" runat="server" />
</td>
<telerik:RadSpell ID="rsMessage" ControlToCheck="txtMessage" ButtonType="None"
UseClassicDialogs="true" FragmentIgnoreOptions="All"
OnClientCheckFinished="checkFinished" runat="server" />
</tr>
Any idea why btnSubmit_Click isn't getting called and how I can fix it?
Try to inject your postback script as :
string script = #"function MySubmit(){" +
this.Page.ClientScript.GetPostBackEventReference(myButton, string.Empty);
"}";
if (!this.Page.ClientScript.IsClientScriptBlockRegistered("myPostBackScript"))
{
this.Page.ClientScript.RegisterClientScriptBlock(typeof(MyPage), "myPostBackScript", script, true);
}
The last like of doSpellCheckStuff() is returning false always, which stops the OnClick event listener from running.