How do you get the checked value of asp:RadioButton with jQuery? - c#

I need to do something like this:
<asp:RadioButton ID="rbDate" runat="server" Text="Date" GroupName="grpPrimary" />
and be able to check the value of the radio button's checked value in jQuery, but my attempts like these don't return true/false.
if ($('[name=rbDate]').attr("Checked"))
if ($('[name=rbDate]').attr("Checked").val())
if ($('[name=rbDate]:checked').val())
A little help?

This is probably the easiest way to do it. The *= searches the whole id attribute for rbDate which takes care of the whole ASP.NET id mangling.
$('input[id*=rbDate]').is(":checked");

While ChaosPandion's answer will work it would be faster to wrap your RadioButtonList in a div like this:
<div id="dateWrapper">
<asp:RadioButton
ID="rbDate"
runat="server"
Text="Date"
GroupName="grpPrimary" />
</div>
Then your jQuery code can be this simple:
var selected = $("#dateWrapper input:radio:checked");

INamingContainer adds a bunch of stuff to the beginning of the id of the actual html.
$('input[id$=rbDate]').attr('checked')
using the [id$=rbDate] bit on the selector tells jQuery that you want the input with an id that ends in rbDate
Now if you had a that you wanted to get the selected value of the entire list you might do something like
$('input[name$=rbDate]:checked').val()
which, were one of the items selected would return the value of the selected , or , in that radio button list.

Here is my JQuery solution that uses the asp.net ID:
var rbSelected = $("#<%= rbDate.ClientID %>").is(":checked");

Related

Gridview Custom controls and javascript functions c#

I have a custom control which is basically a Gridview and its first column is a TemplateField with a checkbox in the header and a checkbox for each of the rows. Clicking on the header checkbox should call some javascript to toggle each of the checkboxes in every row on display... it's a common requirement as we know.
My problem is (I'll go into more detail later) that when I have 2 of these controls on the same page, and I click the checkbox that selects all the chkboxes, the page calls the wrong bit of javascript (which only appears once on the rendered html page) and checks all the checkboxes on the wrong grid !
Here's my code:
<asp:TemplateField>
<HeaderTemplate>
<input type="checkbox" ID="chkSelectAll" onclick="SelectAllCheckboxes(this)"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelected"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
Javascript:
<script>
function SelectAllCheckboxes(chk) {
$('#<%=gridPublishers.ClientID%>').find("input:checkbox").each(function ()
{
if (this != chk) { this.checked = chk.checked; }
});
}
</script>
So, the parent page has 2 of these controls on it. The first grid shows All the publishers and the other shows the publishers that have been selected from the first...
<h2>Selected Publishers</h2>
<cac:GridPublishers id="GridSelectedPublishers" runat="server" CssClass="GridSelectedPublishers" BindSource="DynamicFromSession" ShowMultiSelectCol="true" ShowFilterControls="false" NoRecordsMessage="No Publishers have been selected yet." />
<br /><br />
<h2>All Publishers</h2>
<cac:GridPublishers id="GridPublishers" runat="server" ShowMultiSelectCol="true" CssClass="GridPublishers" />
As I said earlier, the javascript only appears once on the rendered html page (and I understand why) but how can I get each instance of the custom control calling it's own javascript (or an alternative method) so that it only toggles its own checkboxes ??
...
I've also tried adding 2 javascript events and on grid bind trying to find the master checkbox and assign it the correct JS function, but I've searched each cell of the header row, and col 0 (where the control should be) holds 0 controls.
...
I've also tried adding a hidden button that on page load, I can assign it the correct javascript function (that will affect the correct gridview) and then the master checkbox fires the hidden button onClientClick event, but as the page reloads, it gets confused and fires the click event twice and from both grids apparently !
Please help !!
So I guess you realise that this line of code is causing the root problem of selecting the checkboxes in the wrong datagrid:
#<%=gridPublishers.ClientID%>').find
It's always going to pickup gridPublishers, and not GridSelectedPublishers.
So this is the area to fix. What you need to do is make this function a bit more abstract:
<input type="checkbox" ID="chkSelectAll" onclick="SelectAllCheckboxes(this)"/>
The onclick event passes 'this', but that's only a reference to the checkbox which isn't much help.
I'd suggest you try and make it something like this:
<input type="checkbox" ID="chkSelectAll" onclick="SelectAllCheckboxes(this,'GridSelectedPublishers')"/>
And then use the 2nd argument in the javascript function to grab the right datagrid.
Your problem now, is how to get that 2nd argument in there....you may be able to think of your own solution for this, but I would be tempted to make that checkbox an ASP checkbox, and find it during datagrid render and assign it the onClick with Attribute.Add
Making sense?
I've already marked "ben_the_builder's" answer as correct because it got me along the right line.
When I bind my grids I call this function:
private void Register_CheckAllControl_JScript()
{
// THIS IS A WORKAROUND FOR WHEN TWO OF THE SAME CUSTOM CONTROL LIVE ON THE SAME PAGE, EACH CONTROL'S JAVASCRIPT MUST SPECIFY THE ID OF THE CONTROL TO AFFECT
if (gridPublishers.HeaderRow != null)
{
CheckBox chkAll = gridPublishers.HeaderRow.FindControl("chkSelectAll") as CheckBox;
if (chkAll != null)
{
if (this.BindSource == Enumerators.BindSource.DynamicFromSession)
{
chkAll.Attributes.Add("onclick", "SelectAllCheckboxes(this,'GridSelectedPublishers');");
}
else
{
chkAll.Attributes.Add("onclick", "SelectAllCheckboxes(this,'GridPublishers');");
}
}
}
}
To access the "master" checkbox from code behind - it had to be an ASP control. an input control just wasn't recognised when iterating through the header cell collection.
My Javascript needed a little tweaking for the IDs to be correct. The control name I'm passing had to be name it was given on the parent page which belongs in the middle of the three tier final html output name (see the example, it'll make sense...)
My Javascript looks like this now:
<script>
function SelectAllCheckboxes(chk, ctrlName) {
//if ctrlName = "
$("#MainContent_" + ctrlName + "_gridPublishers").find("input:checkbox").each(function () {
if (this != chk) { this.checked = chk.checked; }
});
}
</script>
You want to use parameters. Instead of hard coding #<%=gridPublishers.ClientID%> into your javascript function, use the this parameter you pass to the function to determine the name of the grid view that contains the checkbox, then check everything inside that grid view.

I need help in passing a value from asp:linkbutton and string replacement using JQuery

I have this LinkButton:
<asp:LinkButton runat="server" CssClass="lFilename"
ID="grdlinkFilename" Text='<%#Eval("FILEPATH")%>'
CommandArgument='<%#Eval("FILEPATH")%>' OnCommand="grdlinkFilename_click"
data-id='<%#Eval("FILEPATH")%>'> </asp:LinkButton>
And in my external jquery file I did this:
var result = $("#grdlinkFilename").attr("data-id");
result = result.replace(/D:\\/i, "http://ip/Vdrive/");
result = result.replace(/\\/g, "/");
What I want to do is to pass the value from the <%#Eval("FILEPATH")%> to my external jquery file. Suppose the value of <%#Eval("FILEPATH")%> is d:\folder\img.jpg in jquery.
I want to change from d:\folder\img.jpg to d:\\folder\\img.jpg (which is missing from my code for the jquery file).
Next again using jquery i'm going to change from d:\\folder\\img.jpg to http://ip/Vdrive/folder/img.jpg.
My concerns are:
Is my way off passing the value from my asp:linkbutton to external
js file is correct including the way I call it? as in var result =
$("#grdlinkFilename").attr("data-id");
If the way I pass the value from asp:linkbutton to external js file is correct, how can I convert it's value to let say from "d:\folder\img.jpg" to "d:\\folder\\img.jpg"?
In jQuery you can just call var result $("#grdlinkFilename").data("id");. No need to call it via .attr()
You can use C# to replace the backslashes if required:
data-id='<%#((string)Eval("FILEPATH")).Replace(#"\", #"\\")%>'>
If you want to do this in Jquery.
Before writing jquery like $("#grdlinkFilename").attr("data-id"); you have to add the property called ClienMode="static" to the <asp:LinkButton />
Like
<asp:LinkButton runat="server" ClienMode="static" CssClass="lFilename" ID="grdlinkFilename" Text='<%#Eval("FILEPATH")%>' CommandArgument='<%#Eval("FILEPATH")%>' OnCommand="grdlinkFilename_click" data-id='<%#Eval("FILEPATH")%>'> </asp:LinkButton>
Then only the <asp:LinkButton /> id will not changed after the compilation. The script will be executed. other wise run time the server control ID will be changed. By View the Source you can see the changed id before adding this.
Is my way off passing the value from my asp:linkbutton to external js file is correct including the way I call it? as in var result =
$("#grdlinkFilename").attr("data-id");
Since you're using data- api, the ff. code will do:
var result = $("#grdlinkFilename").data("id");
If the way I pass the value from asp:linkbutton to external js file is
correct, how can I convert it's value to let say from
"d:\folder\img.jpg" to "d:\folder\img.jpg"?
result = result.replace(/\\/g, "\\\\");

how to get <input of type=hidden> with FindControl

I am trying to get the value of a hidden input in code behind with the following code. I am trying to cast it but it cannot find it , any help ?
((HtmlControl)FindControl("contentId"))
I declare it in aspx with the following code:
<input id="contentId" type="hidden" />
I dont want to runat server because i have my own reasons
To access a HTML control at server side (in your C# code), you need to first add the runat="server" attribute. So, your markup should look like
<input type="hidden" id="contentId" runat="server"/>
Now, in the code behind you can use the control by its id contentId itself if the code behind got generated properly.
Please let us know why you are forced to use the FindControl in the first place as it can be accessed by using the id directly.
Update
As per the comment below, the user for some reason is not interested in making this input a server side control. Then the only possibility by which you can read the values at server side is as below. But this is not advised as any changes to the name goes unnoticed and breaks at runtime.
<input type="hidden" id="contentId" name="contentName" runat="server"/>
In Code
this.Request.Forms["contentName"] would return the hidden value.
Try to search it on the page this way
HiddenField hf = (HiddenField)page.FindControl("contentId");
To get the value:
HiddenField h = (HiddenField)Gridview.FindControl("HiddenFieldName");
Then with that you can put it into a string, if you wish to.
Use this code:
string s=((HiddenField)Panel1.FindControl("contentId")).Value;
Here panel is the container control. This may be a grid or anything else or even a master page. But if you are using FindControl, i think the control may be inside some container.
HtmlInputHidden hf = Page.FindControl("contentId") as HtmlInputHidden;
string hfValue = hf.Value;

How to get value of Rad Button which is used like checkbox

I want to get the value of RadButton which is used like checkbox.
<telerik:RadButton ID="RadButtonCheck" runat="server" ButtonType="ToggleButton"
Checked="false" Text="StackOverflow" ToggleType="CheckBox" Enabled="true" AutoPostBack="false">
</telerik:RadButton>
I have read this question and answer and more..
How to get value for checkbox in JQuery?
But
$('#<%=RadButtonCheck.ClientID%>').is(':checked') //always returns false.
How can I get the correct value?
Edited:
Also .attr('checked') attribute returns nothing and it gives error..
The most suitable answer for my question is:
var button = $find("<%= stackoverflow.ClientID%>");
if(button.get_checked())
{
alert("is checked");
}
Just had a look on this page http://demos.telerik.com/aspnet-ajax/button/examples/radiosandcheckboxes/defaultcs.aspx and looking at the rendered html it looks like you can call
$('#<%=RadButtonCheck.ClientID%>').val();
Which should return "Checked" or "Unchecked". It might differ slightly depending on the exact control but as Aristos suggests you need to look at the rendered HTML.
Alternatively use the RAD Controls Client API found here http://demos.telerik.com/aspnet-ajax/button/examples/clientsideapi/defaultcs.aspx and here http://www.telerik.com/help/aspnet-ajax/button-client-side-basics.html in order to access the checked value. I think you need to call .get_checked() method.
All Telerik RadControls have a rich client side API - which includes properties and methods. In your case i assume you want to know on the client side whether the user has checked the RadButton whose toggle type is CheckBox type.
You can listen for the client side OnClientCheckedChanged event. This event will get you the sender i.e. RadButton which was clicked and event args which is of Type radButtonCheckedEventArgs. This contains get_checked() method which will let you know if the checked state is true (meaning checked) or false (meaning not checked). Here is the code snippet to achieve this:
<div>
<telerik:RadButton ID="RadButtonCheck" runat="server"
ButtonType="ToggleButton" Checked="false"
Text="StackOverflow" ToggleType="CheckBox" Enabled="true"
AutoPostBack="false" OnClientCheckedChanged="onClientCheckedChanged">
</telerik:RadButton>
</div>
<script>
function onClientCheckedChanged(sender, args) {
alert(args.get_checked());
}
</script>
Here is the documentation link for the client side event:
http://www.telerik.com/help/aspnet-ajax/button-onclientcheckedchanged.html
Hope this answers your question.
Lohith (Tech Evangelist, Telerik India)
Can you set a name for the radio button and then try to get the checked value by the name? Something like this:
<telerik:RadButton ID="RadButtonCheck" runat="server" ButtonType="ToggleButton" Checked="false" Text="StackOverflow" ToggleType="CheckBox" Enabled="true" AutoPostBack="false" name="myRadio"> </telerik:RadButton>
$('input:radio[name=myRadio]:checked').val();

Get the values of selected checkboxes from an asp checkboxlist in jquery

I am trying to get the selected value (or values) of the checkboxlist. My problem is that I am binding the checkboxlist in c# and it's not rendering with the "Value" attribute as it would if I were to hard code the
<asp:ListItem Value=".." .. />
My checkboxlist looks like this:
<asp:CheckBoxList runat="sever" ID="cblStuff" DataValueField="myID" DataTextField="myName"></asp:CheckBoxList>
So when I try to use jquery and do the follow, it returns only "on" as apposed to "myID". Am I missing something? I was under the impression that is what the DataValueField was for?
Here is the js I am using:
$("checkboxlist selector").change(function() {
$(this).find(":checked").each(function() { alert($(this).val()); });
});
Thanks.
DataValueField is server side property and it will not be rendered in html , so you cannot get the value with jquery or any other client side code.
also check the related question: Where are the DataValueField values for a CheckBoxList stored?
You should be able to get all of the checked items like this:
$("#<%=cblStuff.ClientID%> input[type=checkbox]:checked").each(function(){
var val = $(this).attr("value");
});
I don't think the CheckBox control has a value attribute by default, but the CheckBoxList might. In either case, you can always add a value attribute.
You can use jQuery's attr() method to get any attribute, official or otherwise:
$("checkboxlist selector").change(function() {
$(this).find(":checked").each(function() {
alert($(this).attr('DataValueField'));
});
});
$('#<%= checkboxlist.ClientID %> input:checkbox').change(function () {
if ($(this).is(":checked") && $(this).val() == "DesiredValue")
alert($(this).val());
});
This will check to see if the value has been set to DesiredValue. The event fires whenever the value is changed. You must check to make sure that the item causing the event to fire is checked, and if it is if it has the value you care about.

Categories