to find the value of the radio button checked - c#

hi I have a radio button list inside a repeater , the repeater is inside a Datalist.i need to get the value of the selected radio button. Also I need to select only a single radio in entire datalist using javascript.

You can do it with pure client side JavaScript regardless of Repeater, DataList or anything.
Have this code in your page:
<script type="text/javascript">
function GetSelectedRadioButtonValue(strGroupName) {
var arrInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oCurInput = arrInputs[i];
if (oCurInput.type == "radio" && oCurInput.name == strGroupName && oCurInput.checked)
return oCurInput.value;
}
return "";
}
</script>
Then to get the selected value call the function passing the name of the radio buttons group - all radio buttons with same name considered a group and the browser will let the user select only one of these.
Live test case: http://jsfiddle.net/yahavbr/BL9xJ/

I would use the normal HTML Radio Button control. Everything else is pretty complicated.
Then you can use the following code to figure out which one is selected:
http://remy.supertext.ch/2008/02/find-checked-radio-button-in-aspnet/

Related

Creating and finding dynamic controls on a page

There is a problem to find a dynamic control on a page. The dynamic control is created every time when a user press a button. The button calls the following JavaScript function and create a new components.
<script type="text/javascript">
var uploadCount = 1;
function addFileInput(fName) {
var only_file_name = fName.replace(/^.*[\\\/]/, '');
var $div = $('<div />', {runat: 'server'});
var $cbox = $('<input />', { type: 'checkbox', id: 'attachement' + uploadCount, value: fName, checked: "true", runat: 'server'}).addClass;
var $label = $('<label />', { 'for': 'attachement' + uploadCount, text: only_file_name });
$div.append($cbox);
$div.append($label);
$('#newAttachment').append($div);
$("#uploadCountValue").prop("value", uploadCount);
uploadCount++;
}
</script>
newAttachment is DIV section on the page.
<div id="newAttachement" runat="server" />
The DIV section is situated inside section. The problem is when a user presses the button on the form I can't find the dynamic created components. The following code shows how I try to find the components:
for (int i = 1; i <= Convert.ToInt32(uploadCountValue.Value); i++)
{
if (RecursiveFind(newAttachement, "attachement" + i) != null)
{
... to do something
}
}
public Control RecursiveFind(Control ParentCntl, string NameToSearch)
{
if (ParentCntl.ID == NameToSearch)
return ParentCntl;
foreach (Control ChildCntl in ParentCntl.Controls)
{
Control ResultCntl = RecursiveFind(ChildCntl, NameToSearch);
if (ResultCntl != null)
return ResultCntl;
}
return null;
}
I have detected that Controls count value is always zero in spite of there are dynamic components there.
I would be happy to get any help from us. Thanks.
to find the controls created in the client-end you can't search them in the Page.Controls collection instead try to look for them in the Request.Form[] array
you are creating the dynamic controls in javascript? i.e. you are creating html elements in javascript. It won't matter even if you put a runat="server" attribute in there, because it is still at the client-end. That would not be a part of the viewstate bag, so not populated in the controls collection.
you need to change your logic. create dynamic control in code-behind on button postback.

How to use an ajax modal popup and consume a value from a link?

I've read a few articles regarding getting values back from a modal popup in an ASP .NET page, but they all seem to use JavaScript to accomplish this which isn't really want I want to do if possible.
I have a web user control which has a repeater that I populate from a list into a table. Each row has a link button which has a redirect url with a value as a query string.
Then I have another web user control which is just a link button with a panel and the repeater web user control that once clicked shows the actual modal popup.
Is it possible to get a value from the web user control once the link button on the repeater is clicked without having to redirect to the same page? I basically want to click on the link, show the modal and once closed, want to access the value.
I'm populating the repeater with the links as follows:
string linkUrl = "";
string action = "";
if (Request.QueryString["action"] != null)
{
action = Request.QueryString["action"];
switch (action)
{
case "SetupCompany":
{
linkUrl = "<a href=CreateCompanies.aspx?companyId=";
break;
}
case "ViewCompany":
{
linkUrl = "<a href=ViewCompany.aspx?companyId=";
break;
}
}
}
CompaniesBusinessManager mgr = new CompaniesBusinessManager();
var companies = mgr.GetCompanies(txtCompanyName.Text, txtRegistrationNumber.Text);
if (linkUrl != "")
{
foreach (var c in companies)
{
c.Name = linkUrl + c.Id.ToString() + "&action=" + action + ">" + c.Name + "</a>";
}
}
rptrCompanies.DataSource = companies;
rptrCompanies.DataBind();
if you don't want the page to be redirected, you will need to use javascript.
There is now way you can pass values from different controls without going back to the server.
In case you keep it without the javascript:
I think you need to pass values from one user control to another. I used to accomplish this by firing reachable events between them.
For example:
in your parent view:
<uc:YourUserControl runat="server" ID="UserControl_Test"
OnYourCustomAction="UserControl_YourUserControl_YourCustomAction" />
In your user control:
public event EventHandler<CustomActionEventArgs> YourCustomAction;
also in the same user control create a public trigger method to be access from others usercontrols
public void TriggerCustomActoinEvent(CustomActionEventArgs EventArgs)
{
if (this.YourCustomAction!= null)
{
this.YourCustomAction(this, EventArgs);
}
}
Hope this help, in on my way to home this was from my mind!
Without a page postback or JavaScript it not really possible. If you are using modal popups you are already using JS, so why not just get the value in JS? You could setup an event handler for all repeater buttons and if they are loaded via ajax use something like this to attach the event handler:
$(document).on('click', '.repeaterButton', function(e) {
var valueOfBtnClicked = $(this).val();
// Do something else
});

How can i store the selected tab on a RadTabStrip that can be returned to on back button click

I currently use a hidden input field that is assigned the value of the tab that has just been selected, via javascript, like so:
function onTabSelecting(sender, args) {
var tab = args.get_tab(); //get selected tab
document.getElementById("MainContent_hdnPreviousTab").value = tab.get_text(); //assign value to hidden field
if (tab.get_pageViewID()) { //ignore
tab.set_postBack(false);
}
}
I then use this assigned value when the page is returned to, on client-side (ajax) PageLoad() event:
<script type="text/javascript" language="javascript">
var runOnce = false;
function pageLoad() {
if (!runOnce) {
var lastTab = document.getElementById("<%= hdnPreviousTab.ClientID %>");
if (lastTab.value) {
if (tabStrip) {
var tab = tabStrip.findTabByText(lastTab.value);
if (tab) {
tab.click();
}
}
}
runOnce = true;
}
}
</script>
Currently in IE this works fine (I know right?), the value that was previously set in javascript is still there and i am able to lcoate the tab that the user left the page on. However in FF, Chrome, etc. i have no such luck. The hidden field is returned to it's empty state (value = "") regardless of utilising viewstate or not.
Very curious as to whether anyone has an alternative method that would be appropriate in this situation. Please let me know if this is unclear.
Many thanks.
You could use localstorage.
localStorage.setItem('tab', value);

Textbox onchange event

So I have a text box, where I add an onchange event of markAsException.
My javascript is -
function markAsException(recordID) {
//alert("Exception");
//mark exception column
document.getElementById("ctl00_cpMain_lblScrollException_" + recordID).innerText = "Exception";
document.getElementById("ctl00_cpMain_lblScrollException_" + recordID).style.color = "#FF0000";
document.getElementById("ctl00_cpMain_tdScrollException_" + recordID).style.backgroundColor = "#99CCFF";
//enable comments ddl and remove blank (first item)
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).disabled = false;
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).focus();
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).options[0] = null;
}
What I want to do is, when a user changes the value in a textbox, to mark a column as "Exception", and then focus a drop down list where they have to chose the reason for the exception.
This is what happens.. If I am on that text box and change it, then tab, it tabs to the drop down list.
However, if I change the value and then simply click in another text box on the form, I don't focus the drop down list.
How would I accomplish that?
I would suggest using JQuery's change() function.
The advantage is that it will be more stable across different browsers.
Something like:
$('#<%= TextBox1.ClientID %>').change(function(){
// extract the recordID from the textbox - perhaps with an attribute?
markAsException(recordID);
});
My comment was getting longer so I'm expanding:
Take a look at the JQuery documentation for setting this up as the page finishes loading. If tb is the ID of your textbox your selector would be
$('#<%= tb.ClientID %>')
I would suggest you replace your code and use
tb.Attributes.Add("recordID", recordId.ToString());
This will add the ID you need onto the textbox tag. Once you're in the function I outlined above you can use the following selector to get the recordID in javascript
var recordID = $('#<%= TextBox1.ClientID %>').attr('recordID');
All together
$(document.ready(function(){
$('#<%= tb.ClientID %>').change(function(){
var recordID = $('#<%= tb.ClientID %>').attr('recordID');
if(recordID){
markAsException(recordID);
}
});
});

ASP.NET count boxes and then execute popup from same button

Ok, I hope I can explain this well enough.
I have one or more third party Up/Down Spinner+Textbox controls on my page that are black boxes that I can't change the source for.
I want the user to change the UpDownControl contents to choose a quantity and then click a calendar button which will:
Add the quantity of all Up/Down boxes.
Call a javascript popup to display a calendar with the count from step 1 in the url "...calendar.asp?qty=5".
My problem is getting the two steps to execute in the same click. As it stands I can click the button once and it counts
the items and adds them to the popup string and then I have to click it a second time to actually execute the JS popup window.
The code was originally written to "load up" the counts into a second button and then programmatically click it but that looks
like a popup to the browsers since the user didn't click that button.
Here is what I have so far that almost works --
On my page:
<asp:ImageButton ID="btnPrepCal" runat="server" Text="PrepCal" OnClick="btnPrepCal_Click" ImageUrl="~/images/Calendar.gif"/>
In code behind:
public void btnPrepCal_Click(object sender, EventArgs e)
{
StringBuilder sbParams = new StringBuilder();
int TotalQty = 0;
int basketItemCount = 0;
int rowIndex = 0;
string Sku = string.Empty;
foreach (GridViewRow varRow in VariantGrid.Rows)
{
int qnty = GetControlValue(varRow, "Quantity", 0);
if (qnty > 0)
{
basketItemCount++;
string optionList = (string)VariantGrid.DataKeys[rowIndex].Value;
ProductVariant variant = _VariantManager.GetVariantFromOptions(optionList);
if (variant != null)
{
BasketItem basketItem = GetBasketItem(optionList, varRow);
if (basketItem != null)
{
TotalQty += basketItem.Quantity;
Sku = variant.Sku;
}
}
}
rowIndex++;
}
if(Sku.Length > 4) Sku = Sku.Substring(0,4);
sbParams.Append(string.Format("?sku={0}&Qty={1}", Sku, TotalQty));
string popup = string.Empty;
popup = string.Format("window.open('http://trustedtours.org/store/egalaxycalendar.asp{0}','Reservation Calendar','width=265,height=465')",sbParams.ToString());
btnPrepCal.OnClientClick = popup;
}
I'm new to .NET and web programming so I'm probably going at it totally backwards so any help is appreciated. I apologize if it's not clear what I'm trying to do or how. If you need any more info please ask - the rest of the file is a lot of shopping cart mumbo jumbo so I left it out, I hope it's enough.
---- update ----
After looking at the referenced pages I get:
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript>" + popup + "<script>");
cs.RegisterStartupScript(cstype, "PopupCalendar", cstext1.ToString());
And I believe this is added after I set the value of popup near the bottom of my Click handler above, removing the OnClientClick part, right?
Should this popup the other window on a page reload after clicking the button? (I hate being a newb and asking what's probably obvious questions.)
You can accomplish what you're aiming for using the ClientScriptManager.RegisterStartupScript method. Instead of assigning the OnClientClick method of the button to your JS popup code, set that code to run when the page is reloaded using the RegisterStartupScript method.
This page has some good examples: http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx
Ken is correct. To add to his answer and clarify why your code was not working - you were assigning the click-handler of your button to do a popup, but only after it was clicked. This is why you only saw the popup after the 2nd click - the handler was not there the first time you clicked it.

Categories