how to call this Jquery function on Button Click event? - asp.net

I wanna call this jquery function in ASP.NET on button click event
var doRedirect = function() { location.href='http://www.example.com' };
$("#button1").click(function() {
$("#label1").show();
window.setTimeout("$('#label1').fadeOut('slow', doRedirect)", 10000);
});

If your jQuery is inline, you can do the following:
var doRedirect = function() { location.href='http://www.example.com' };
$("#<%=button1.ClientId%>").click(function() {
$("#<%=label1.ClientId%>").show();
window.setTimeout("$('#<%=label1.ClientId%>').fadeOut('slow', doRedirect)", 10000);
});
If it isn't inline (i.e. in a file), you will need to get the client control Id's you want to use in a different way, for example wrapping them in a div with an ID and selecting them through the div:
<div id="myId">
<asp:Label runat="server" id="label1" />
<asp:Button runat="server" id="button1" />
</div>
var doRedirect = function() { location.href='http://www.example.com' };
$("#myId input").click(function() {
$("#myId span").show();
window.setTimeout("$('#myId span').fadeOut('slow', doRedirect)", 10000);
});
Note that I am using the output HTML element types as the descendant in the jQuery selector.

Related

asp.net and jQuery ui dialog issue on modal:true

I have a div that contains an Asp checkboxlist and is opened by jquery ui dialog . I need to manage the postback too, so I add
.parent().appendTo($("form:first"));
The problem is that when dialog is opened all DOM is disabled, it seems that modal:true is extended to all DOM
this is aspx code :
<script type="text/javascript">
$(function () {
$("#modalDialog").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Salva": function () {
$("[id*=btn_save]").click();
},
"Annulla": function () {
$(this).dialog("close");
}
},
close: function () {
}
});
$("#modalDialog").parent().appendTo($("form:first"));
});
</script>
<div id="modalDialog" >
<asp:CheckBoxList ID="ckb_eventi" runat="server" DataTextField="NOME" DataValueField="ID_CASSA">
</asp:CheckBoxList>
</div>
<asp:Button ID="btn_save" runat="server" Text="Salva" style = "display:none" OnClick = "btn_save_Click" />
I solved using jquery ui dialog option :
appendTo: "form:first"
instead of using
$("#modalDialog").parent().appendTo($("form:first"));

jquery dialog form with asp:hyperlink

I have an issue in implementing the JQuery dialog with asp.net form. When I click on #hlChangePassword nothing happens. This is my code below:
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#hlChangePassword').click(function () {
var dlg = jQuery('div#ChangePass').dialog({
width: 500,
height: 500,
modal: true,
buttons: {},
open: function (event, ui) {
$(".ui-dialog-titlebar-close").hide();
}
});
dlg.parent().appendTo(jQuery("form:first"));
});
});
</script>
html
<asp:HyperLink ID="hlChangePassword"
runat="server" NavigateUrl="#">Change Password</asp:HyperLink>
<div id="ChangePass" style="display:none;">
//The content
</div>
I don't know what is the problem. Please help me.
User event.preventDefault(); to prevent the post back as follows
jQuery(document).ready(function () {
jQuery('#hlChangePassword').click(function (event) {
var dlg = jQuery('div#ChangePass').dialog({
width: 500,
height: 500,
modal: true,
buttons: {},
open: function (event, ui) {
$(".ui-dialog-titlebar-close").hide();
}
});
dlg.parent().appendTo(jQuery("form:first"));
event.preventDefault();
});
});
As hlChangePassword is a server control so it will post back. to overcome this you should use event.preventDefault.
Also you are using id selector which can change at run-time due to master page or user-control. So use server id or static id for the link as follows if you are using asp.net 4.0 or above as follows
ClientIDMode="Static"
<asp:HyperLink ID="hlChangePassword" ClientIDMode="Static"
runat="server" NavigateUrl="#">Change Password</asp:HyperLink>
Bingo...
script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js">
add above line it wont work without ui.js.

How we can group radio buttons inside a repeater?

I have a radio button inside a repeater as follow.
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:RadioButton ID="rbtnCityName" runat="server" Text='<%# Bind("CityName") %>'
GroupName="Cities" />
</ItemTemplate>
</asp:Repeater>
Now problem is that how I can select a single radio button across multiples.
Even though I have given a groupname for radio button, I am not able to select any of them.
<script type="text/javascript" language="javascript">
function fnCheckUnCheck(objId)
{
var grd = document.getElementById("<%= rpt.ClientID %>");
var rdoArray = grd.getElementsByTagName("input");
for(i=0;i<=rdoArray.length-1;i++)
{
if(rdoArray[i].type == 'radio')
{
if(rdoArray[i].id != objId)
{
rdoArray[i].checked = false;
}
}
}
}
</script>
call this function on click of radiobutton
onclick="fnCheckUnCheck(this.id);"
the best solution for me was to simlpy create an html input control inside the repeater:
<input type="radio" name="yourGroup" value='<%# Eval("Value") %>'/>
got the solution from Radio button repeater problem solved
Just adding another solution in case someone else is still running into this in 2020...
It does use JavaScript.
If you inspect the radio button in the browser's dev tools you'll see that the RadioButton control is rendered as a span with an input inside it, just like other input controls such as CheckBox.
So this:
<asp:RadioButton runat="server" class="my-class" name="myGroup" value="myGroupOption1" />
Ends up as something like this:
<span name="myGroup" class="my-class">
<input id="(long generated id)" type="radio" name="(generated name)" value="myRadioButton">
</span>
Notice I didn't use ASP.NET's GroupName attribute. If you use that it will end up as a name attribute on the input, replaced with the generated value that is causing problems here. Just use the regular name attribute and it gets moved to the span.
Now, to fix the names in the browser you can do something like this. I used JQuery, but you could accomplish the same with pure JavaScript.
$(document).ready(function () {
$('.my-class').each(function () { // find all the spans
if ($(this).attr('name')) {
var groupName = $(this).attr('name'); // save the group name
$(this).children('input').each(function () { // find the input
$(this).attr('name', groupName); // fix the name attribute
});
}
});
});
Now the radio buttons are grouped properly.
So add a unique CSS class to your radio buttons and run that function on page load.
$('#SubmitAnswers').click(function () {
var names = [];
$('input[type="radio"]').each(function () {
// Creates an array with the names of all the different checkbox group.
names[$(this).attr('name')] = true;
});
// Goes through all the names and make sure there's at least one checked.
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if (radio_buttons.filter(':checked').length == 0) {
// alert('none checked in ' + name);
$('#Group'+ name).css("visibility", "visible");
}
else {
// If you need to use the result you can do so without
// another (costly) jQuery selector call:
var val = radio_buttons.val();
$('#Group' + name).css("visibility", "hidden");
}
}
});

Get the rowIndex of an ASP.Net Gridview using jQuery

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") );
})
}
);

Check box in gridview with button

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.

Resources