ASP.NET Gridview Checkbox column - Onclick and jquery - c#

On click of checkbox, I need to retrieve immediate parent span's class value:
The checkbox column is defined in an ItemTemplate as:
<asp:CheckBox CssClass='<%# Eval("ID") %>' Checked='<%# Eval("IsSelected") %>'
Text="" runat="server" onclick="CartItemCheckClicked()" />
The JS function is defined as:
function CartItemCheckClicked() {
alert($(this).parent().attr('class')); //Undefined
//alert($(this).attr('id')); //Undefined
}
Ouput Sample HTML
<span class="283"><input type="checkbox" onclick="CartItemCheckClicked();" checked="checked" name="grvShoppingCart$ctl02$ctl00" id="grvShoppingCart_ctl00_0"></span>
But the result is always 'undefined'. How do I access the checkbox or parent span?

Just pass checkbox to click function:
onclick="CartItemCheckClicked(this);"
And in js file than:
function CartItemCheckClicked(chk) {
alert($(chk).parent().attr('class'));
}

Related

Only one checkbox checked in repeater

I have a repeater with 1 checkbox for every item. I want to only have one checked at a time.
The checkboxes is asp:checkbox, don't know if it makes any difference.
I tried with some jquery but it doesn't seem to work.
<asp:Repeater runat="server" DataSourceID="SqlDataSource1" ID="repeater1">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" Checked='<%# Eval("carousel_check")%>'/>
</ItemTemplate>
</asp:Repeater>
I have tried to give the checkbox a cssclass (checked_button) and then this script.
$(document).ready(function () {
$('.checked_button').change(function () {
if ($(this).is(':checked')) {
$('.radio-similar').not(this).removeAttr('checked');
};
});
});
ASP.Net Checkbox is rendered inside span tag.
<span class="checked_button">
<input id="MainContent_Repeater1_CheckBox1_2"
type="checkbox" name="ctl00$MainContent$Repeater1$ctl02$CheckBox1">
</span>
So the selector should be .checked_button input. Then uncheck all checkboxes, and check only the one triggered the click event.
$(function() {
$(".checked_button input").click(function () {
$('.checked_button input').attr("checked", false);
$(this).prop("checked", true);
});
});

How to pass a hidden field value on javascript function inside repeater control

I tried a lot but couldn't figure it out. I wanted to pass data on my javascript function.
I am saving data on hidden filed. what I want as soon I click on my button it will call javascript function & pass my hidden field vlaue.
<asp:Repeater ID="rptGallary" runat="server" >
<ItemTemplate>
<asp:HiddenField ID="hfsportsmanfeedid" runat="server" value='<%# DataBinder.Eval(Container.DataItem,"SportsmanFeedId") %>'/>
<asp:Button ID="btnLike" runat="server" Text="Like" OnClientClick="Test("How to pass here"));" />
</ItemTemplate>
</asp:Repeater>
Thanks for your help.
You just need to pass the clicked element on Test button click
Try with this code:
HTML/ASPX Markup
<asp:Button ID="btnLike" runat="server" Text="Like"
OnClientClick="Test(this);" />
Javascript
function Test(element){
var $btn = $(element) // Gets clicked button
var hiddenBValue = $btn.prev().val(); // Gets hidden element value
}
Docs
prev()
This should work!
You can pass it like,
<asp:HiddenField ID="hfsportsmanfeedid" runat="server" value='<%# DataBinder.Eval(Container.DataItem,"SportsmanFeedId") %>'/>
<asp:Button ID="btnLike" runat="server" Text="Like" OnClientClick="Test('<%# DataBinder.Eval(Container.DataItem,\"SportsmanFeedId\") %>'));" />
SCRIPT
function Test(value){
alert(value);
}
Or use prev() like,
<asp:Button ID="btnLike" runat="server" Text="Like" OnClientClick="Test(this));" />
SCRIPT
function Test(ths){
alert($(ths).prev().val());
}
Do it like this-
<asp:Button ID="btnLike" runat="server" Text="Like" OnClientClick="javascript:Test(document.getElementById('hfsportsmanfeedid').value);" />
get the value of hidden field from repeater rptGallary_ItemCommand event and pass that to java script
protected void rptGallary_ItemCommand(object source, RepeaterCommandEventArgs e)
{
//add command name to btnLike button let it bet test here
if (e.CommandName == "test")
{
HiddenField hiddenfield = (HiddenField)e.Item.Parent.Parent.FindControl("hfsportsmanfeedid");
//pass that to javascript
}
}

Getting Gidview Hidden field value on button click in ASP.NET

I have a Gridview dtAppend. I want that when I press delete button the selected row record should be deleted from users table.
I first used button field in gridview, as:
<asp:ButtonField Text="Delete" CommandName="DeleteRow" ControlStyle-CssClass="btn btn-danger btn-small" ControlStyle-ForeColor="White" />
<asp:TemplateField visible="false" ItemStyle-Width="0px">
<ItemTemplate>
<asp:HiddenField ID="HiddenField" Visible="false" runat="server" Value='<%# Eval("userId") %>' />
</ItemTemplate>
</asp:TemplateField>
My client says to show JavaScript alert and on clicking yes the record should be deleted. I cannot write onClientClick for button field so I am being forced to use normal Asp button.
on rowCommand of gridview I am getting the hidden field value in this code
if (e.CommandName == "DeleteRow")
{
GridViewRow row = dtAppend.Rows[Convert.ToInt32(e.CommandArgument)];
hidden1 = (HiddenField)row.Cells[6].FindControl("HiddenField");
string text = Convert.ToString((HiddenField)row.Cells[6].FindControl("HiddenField"));
Session["dtIdDel"] = hidden1.Value;
}
i am getting thew value in Session but i need above code working Button_ClickEvent like below
protected void deleteButton_Click(object sender, EventArgs e)
{
GridViewRow row = dtAppend.Rows[Convert.ToInt32(e.CommandArgument)];
hidden1 = (HiddenField)row.Cells[6].FindControl("HiddenField");
string text = Convert.ToString((HiddenField)row.Cells[6].FindControl("HiddenField"));
Session["dtIdDel"] = hidden1.Value;}
this is where 'e.CommandArgument' gives Error
I cannot use the above code in normal button click as it gives error in e.CommandArgument
Any help?
Simply you can remove visible="false"
<asp:HiddenField ID="HiddenField" runat="server" Value='<%# Eval("userId") %>' />
You Better Remove Visible="false" . Because, the value that has to be binded for hidden field will not be binded in to the field if Visible="false" is there. Any how its a hidden field, so make it Visible="true"
EDIT :
How you handled the RowDataBound event of the Grid, are you assigning the CommandArgument for each row, other wise the above concept will not work in Paging. Refer as below
Ex : -
Button btnMail = (Button)e.Row.FindControl("lnkMail");
btnMail.CommandArgument = e.Row.RowIndex.ToString();
I think this would be easy way, instead of using hidden field.
<asp:LinkButton CommandArgument='<%# Eval("userId") %>' OnClientClick="if (!confirm('Are you sure you want delete?')) return false;" CommandName="DeleteRow" ID="eliminar" runat="server" Text="delete"/>
if (e.CommandName == "DeleteRow")
{
int userId = Int32.Parse(e.CommandArgument.ToString());
}
You can simply send ID as command argument
or
Try the code as below:
var ID = int.Parse(((HiddenField)item.FindControl("HiddenField1")).Value);
sql = "delete from tablename where id=" + ID;

When checkbox checked get datagrid value using jquery

I have a checkbox template field within a gridview in c#, this field also has a hidden field with the id behind it. I want to use jQuery to raise an event on click of the checkbox to grab a datakey value so I can run a query through jQuery and add the checked item to the database. I have seen examples that get datakeys when an overall button is clicked but I want this to happen on each checkbox clicked within the gridview. I currently get "undefined" when trying to access the id.
C# within the gridview
<ItemTemplate>
<asp:CheckBox ID="CheckBox" CssClass="checkbox" runat="server" />
<asp:HiddenField ID="idnum" runat="server" Value='<%# Eval("id") %>' />
</ItemTemplate>
jQuery
$(document).ready(function () {
var gridResults = document.getElementById('<%= grdResults.ClientID %>');
$("form input:checkbox").click(function (e) {
var id = $(this).next('#idnum').val();
alert(id);
return false;
});
});
If there are multiple fields with ID="idnum" you should probably change that to class="idnum". After adding the class you could get the value using:
var gridResults = $(e.target).next('.idnum').val();
If idnum is just an example which is different for each field, you can just use var id = $('#idnum').val();
EDIT: changed e.target.next('.idnum').val(); to $(e.target).next('.idnum').val(); to convert the element to jQuery object
//This is the script to get datakeyname value on check box check event inside GridView
<script type="text/jscript">
$(document).ready(function () {
var gridResults = document.getElementById('<%= grdCateogry.ClientID %>');
$("form input:checkbox").click(function (e) {
var id = $(this).next($('#IDVal')).val();
alert(id);
return false;
});
});
</script>
//This is the GridView
<asp:GridView ID="grdCateogry" DataKeyNames="CategoryId" runat="server">
<Columns>
<asp:TemplateField HeaderText ="Try" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("CategoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Problem with usage of RadioButton in GridView in ASP.NET

<asp:TemplateField HeaderText="Select One">
<ItemTemplate>
<input name="MyRadioButton" type="radio" />
</ItemTemplate>
</asp:TemplateField>
aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow di in GridView1.Rows)
{
RadioButton rad = (RadioButton)di.FindControl("MyRadioButton");
//Giving Error:Object reference not set to an instance of an object.
if (rad.Checked&&rad!=null)
{
s = di.Cells[1].Text;
}
}
Response.Redirect("applicants.aspx?form=" +s);
}
I couldn't get the row which is selected in RadioButton. Can you help me with this please.
You can only use FindControl with server-side controls. Replace your <input> HTML element with an ASP.NET radio button, e.g:
<asp:RadioButton ID="MyRadioButton" runat="server" ... />
you have to use runat="server"
<input name="MyRadioButton" type="radio" runat="server" id="MyRadioButton" />
As already mentioned, add runat="server" and change order of conditions evaluated from if (rad.Checked&&rad!=null) to if (rad!=null && rad.Checked)
By the way it's not so easy to make radiobuttons in GridView column exclusive. Look at this link if you will stumble on problem: Adding a GridView Column of Radio Buttons

Categories