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

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();

Related

Showing button on jquery page load event is not working

I am displaying button on jquery page load event but it is not working. After the page is rendered, it is not visible.
It works fine if i set the visibility in code behind Page Load event.
Jquery
function pageLoad() {
$('#btnSwitchDistributor').css({ 'visibility': 'visible', 'display': 'inline-block' });
}
Html
<asp:Button ID="btnSwitchDistributor" runat="server" Text="Switch Distributor" Visible="false" />
According to MSDN, when you set Visible="false" in your server-side code then the element is not rendered to the client at all. Which means your button isn't "invisble" on the resulting page, it doesn't exist on the resulting page. No JavaScript code can interact with an element that isn't present.
It sounds like instead you want to apply a style to the control:
<asp:Button ID="btnSwitchDistributor" runat="server" Text="Switch Distributor" style="display:none;" />
Aside from that, there are two two potential issues here which I can't necessarily confirm from the content of the question, but which you'll want to check...
The ID value you're looking for is the server-side object's ID. This may not necessarily be the client-side id of the resulting HTML element. Examine the page source to see the client-side id. If it's different then you may need to set it explicitly using the ClientID property.
Do you ever call pageLoad() in your JavaScript code? If not then, well, you'd need to do that. I assume in the document.ready event handler? For jQuery that may be as simple as: $(pageLoad)
Just remove the visible html attribute and the JQuery css.

C# - How to change value of textbox on focus

I'm writing an application in C#. I would like to replace the value for the TEXT property after the user clicks (focuses) on a textbox. I would like to set the TEXT value to be blank instead of the words "ENTER NAME HERE" when they click to edit the textbox.
Front-end:
<asp:TextBox Text="ENTER NAME HERE" OnClick="MyTextboxID_OnClick" ID="MyTextboxID" runat="server"></asp:TextBox>
Code-behind:
protected void MyTextboxID_OnClick(object sender, EventArgs e)
{
MyTextboxID.Text = "";
}
I tried to find the answer to this question but the answers didn't quite match what I wanted to do.
I was hoping C# had something similar to Javascript's "OnClick" or "OnFocus" events. I added the OnClick event to the textbox for illustration purposes. This OnClick event doesn't work.
Thank you in advance for your help!
Remember that ASP.NET is primarly server-side. Actions that run in C# require a post-back to the server. The impact of this on a page can be mitigated somewhat by using AJAX, but this is why you don't see an "OnClick" event off the ASP control.
However, you can still use the Javascript "OnClick" event. Since Javascript runs on the client, and the interaction in this instance is entirely handled on the client, you should just use that.
If you are not comfortable using Javascript, you might want to look at TextBoxWatermark server side control.
It is available NuGet.
<asp:TextBox OnClick="MyTextboxID_OnClick"
ID="MyTextboxID" runat="server">
</asp:TextBox>
<ajaxToolkit:TextBoxWatermarkExtender ID="TBWE2" runat="server"
TargetControlID="MyTextboxID"
WatermarkText="ENTER NAME HERE"
WatermarkCssClass="watermarked" />
You should simply use the following Placeholder="Enter text here."
Option One:
<asp:Textbox id="txtName" runat="server" placeholder="Enter name here." />
Option Two:
$("#<%= txtName.ClientId %>").setAttribute('placeholder', 'Enter name here.');
$("#<%= txtName.ClientId %>").attr('placeholder', 'Enter name here.');
For the Javascript implementation, you would simply place that in your View and wrap it in: <script type="text/javascript"></script>. Those are the ideal approaches to display text which clears on focus.
You could also utilize the Tooltip. Hopefully these examples assist you. Important note, I have no issues with compatibility in IE 8 with the Placeholder. Also these approaches won't force a Postback which can occur due to Server-Side. Which would force you to either do a Postback or implement a Update Panel / Ajax to hide the Postback.
Plugin: https://github.com/mathiasbynens/jquery-placeholder
Why don't you use the place holder attribute and not have to worry about replacing the text at all. This would show when the text box is empty but disappear on focus

How to keep the Text of a Read only TextBox after PostBack()?

I have an ASP.NET TextBox and I want it to be ReadOnly. (The user modify it using another control)
But when there is a PostBack(), The text get reset to an empty string.
I understand that if you set the ReadOnly property to True of a TextBox it's content does not get saved through PostBack().
Is there a way to keep the content after PostBack() and make the TextBox not editable by the user?
I tried to set the Enabled property to False,But still the content doesn't save after PostBack().
Another solution I found and easier one:
Add this to the Page Load method:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("readonly", "readonly");
}
Have your other control store the value in a hidden field, and on postback, pull the value from the hidden field and push it into the textbox on the server side.
txtStartDate.Attributes.Add("readonly", "readonly"); on pageload in the best of the best solutions ,instead or Javascripts,hidden variables,cache,cookies,sessions & Caches.
Get the value using Request.Form[txtDate.UniqueID]. You will get it !!
I've had this same issue but using Knockout binding 'enable' and ASP.Net Server Control Text.
This way:
<asp:TextBox ID="txtCity" runat="server" required="required" class="form-control" placeholder="City" data-bind="value: city, enable: !hasZipCode()"></asp:TextBox>
However, when the form was submitted this field value was always empty. This occurred, I presume, because if the control is disabled, it is not persist on the ViewState chain.
I solved replacing bindig 'enable' by 'attr{ readonly: hasZipCode}'
<asp:TextBox ID="txtCity" runat="server" required="required" class="form-control" placeholder="City" data-bind="attr{ value: city, readonly: hasZipCode }">/asp:TextBox>
Here is a way to do it with javascript in the onfocus event of the Textbox itself.
Doing it like this with javascript has the advantage that you don't need to do it in code behind, which can be difficult if you need to do it in gridviews or similar.
This javascript code is only tested on Internet Explorer and certain parts of it will only work on IE, like for example the createTextRange part which is there just to make the caret end up at the beginning of the text in the Textbox, but that part can be skipped if not needed.
If the core of this technique works on other browsers then it should be possible to make the code cross browser. The core of the idea here is the blur after setting readonly and then a timeout to set the focus again.
If you only set readonly then it does not become readonly until next time you give the Textbox focus.
And of course, the code can be put into a function instead which is called with "this" as argument.
<asp:TextBox
ID="txtSomething"
runat="server"
Text='<%# Bind("someData") %>'
onfocus="
var rng = this.createTextRange();
rng.collapse();
rng.select();
if (this.allowFocusevent=='0') {return;};
this.allowFocusevent='0';
this.readOnly=true;
this.blur();
var that=this;
setTimeout(function(){that.focus()},0);
"
/>
Set the ContentEditable property of textbox to false ContentEditable="false"..
It wont allow you to edit the contents of the textbox
ie;will make the textbox readonly and
also will make the value stay in the textbox after postback..
I think its the easiest way to do it..

Passing parameters into a ASP.Net Button control when clicked

I have an asp button (the code is below). I have the event handler working, but I want to pass a string (which is the result of a javascript function) into the event handler function. Is there a way to do that?
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Run" />
Normally the way you would do this is to have you javascript modify an input control so that the value will be posted back with the Button click. If you want the user to visually not be able see the data that your javascript is modifying to post back then you can write it to a HiddenField.
You can use the OnClientClick to setup the javascript to run before the postback happens to ensure your modified value is put into the input control. Eg:
<asp:Button ID="yourButton" runat="server" Text="Click Me!"
OnClientClick="YourFunctionToAddStringToControl(); return true;"
OnClick="yourButton_Click" />
So you just need to swap the call to YourFunctionToAddStringToControl with your modified javascript function that is writing the value to a HiddenField or another input control. Then update your server side click handler to access the field.
Side Note: When using javascript to write to server side controls such as HiddenField, don't forget to use <%= yourHiddenField.ClientID %> to get the correct control name.
Not in the way you're asking.. However...
You CAN add an ASP:HiddenField, and use Javascript to modify the value of the HiddenField to be your string. Then you can access this in your Button Click event.
An example can be found here.

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

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

Categories