Tag Archives: RadioButton

[RESOLVED]No overload for method 'RadioButtonFor' takes 1 arguments

I am using Radio button list to select either one options:

.cshtml:

if (Model.UserAccountSummary != null && Model.UserAccountSummary.Any())
     {
         foreach (var item in Model.UserAccountSummary)
         {
             <tr>
                 <td>
                     @Html.RadioButtonFor(modelItem => item.user_relationship_customer)@item.USER_RELATIONSHIP_OPTION1_Text

                     @Html.RadioButtonFor(modelItem => item.user_relationship_customerAndChildren)@item.USER_RELATIONSHIP_OPTION2_Text
                 </td>
             </tr>
         }
     }

How can i make this work?

Thanks

 

You need to pass the value of the radio button if it is checked. You can pass the same one as value

@Html.RadioButtonFor(modelItem => item.user_relationship_customer, item.user_relationship_customer)

PS: if you want model binding to work properly after posting, use for loop instead of foreach

The problem is simple, the extension method "RadioButtonFor", does not have
overloaded method with single argument
, where you are passing a single argument alone. That is the problem is your code. Change your code accordingly.

If you take a look at the available constructors for the RadioButtonFor() HTML Helper, you’ll see that all three of them require at least 2 parameters to be used :

RadioButtonFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>,
Object)

This constructor requires a mapping to your Model as the first parameter and a value to be stored for the Radio Button in the second. You would likely want to use something like :

@Html.RadioButtonFor(modelItem => item.user_relationship_customer, item.USER_RELATIONSHIP_OPTION1_Text)@item.USER_RELATIONSHIP_OPTION1_Text

RadioButtonFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>,
Object, IDictionary<String, Object>)

This constructor also accepts a mapping as the first parameter along with a value for the second, and adds a third parameter that will allow you to define htmlAttributes that you want to assign to the Radio Button that is rendered :

@Html.RadioButtonFor(modelItem => item.user_relationship_customer, item.USER_RELATIONSHIP_OPTION1_Text, new { @class = "yourClass" })

RadioButtonFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>,
Object, Object)

The final constructors is basically a rewritten equivalent of the one above as it accepts the same number of objects but instead uses an object for the htmlAttributes parameter instead of a Dictionary<String,Object>. The above is likely a bit easier to read.

[RESOLVED]Custom Radio button with Validation Message

Hi

i am using custom Radio buttion method and also validation message.
Validation is working fine but validation message is not displaying.

my custom method,

public
static
MvcHtmlString
RadioButtonForSelectList<TModel, TProperty>(

this
HtmlHelper<TModel>
htmlHelper,
Expression<Func<TModel,
TProperty>> expression,
IEnumerable<SelectListItem>
listOfValues)

        {

           var
metaData =
ModelMetadata.FromLambdaExpression(expression,
htmlHelper.ViewData);

           var
sb =
new
StringBuilder();

           if
(listOfValues !=
null)

            {

           foreach
(
SelectListItem
item
in
listOfValues)

                {

               var
id =
string.Format("{0}_{1}",
metaData.PropertyName, item.Value);

               //
Create and populate a radio button using the existing html helpers

               var
label = htmlHelper.Label(id,
HttpUtility.HtmlEncode(item.Text));

               var
radio = htmlHelper.RadioButtonFor(expression, item.Value,
new
{ id = id }).ToHtmlString();

               //
Create the html string that will be returned to the client

               //
e.g. <input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line1</label>

                    sb.AppendFormat("<div
class="RadioButton">{0}{1}</div>"
, radio,label);

                }

            }

          return
MvcHtmlString.Create(sb.ToString());

        }

My view part,

@Html.RadioButtonForSelectList(z=>@ques.Q_id,
new

SelectList(@ques.ddl_values,
"Domn_CD",
"Domn_desc")) 

@Html.ValidationMessage(@ques.Q_id.ToString())

 

Rendered part-

<div class="RadioButton">

<input name="ques.Q_id" class="input-validation-error" id="Q_id_ISACC" type="radio" data-val-required="The Q_id field is required." data-val="true" data-val-number="The field Q_id must be a number." value="ISACC"/> <label id="Q_id_ISACC"> </div>

<div class="RadioButton"> <input name="ques.Q_id" class="input-validation-error" id="Q_id_ISACC" type="radio" value="ISACC"/> <label id="Q_id_ISACC"> <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="32"/> </div>

i need validation on this,Valis is YES,NO type.
if its not checked anyone value,it should display error message.

how can i achieve? please help me on this

Thanks,

Sundar.

 

Search for iclientvalidatable in mvc

Hi imran,

i am new to mvc. i am not aware on that.Could you plz give me some simple sample code?

It will be very helpfull for me.

 

Thanks,

Sundar.

Hi Sundar,

Sundar1987

<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="32"/> </div>

The reason for that issue is that you specify the value for ValidationMessage method.

You need specify the name (ques.Q_id).

@Html.ValidationMessage("ques.Q_id")

Best Regards

Starain

Hi Starain,

Thanks for your reply.its working fine. So name is more important.

Thanks,

Sundar.

[RESOLVED]write calculated value to table (asp.net mvc)

I am new to MVC …

I created a simple application to calculate the score. There are 2 sets of radio buttons. User will select selection option and it will calculate the score from the selections. I am able to do all of that but I want to write the calculated score to a field
of the record. How can I do that?

Simplified table as below:

ID   Name       RadioSelected1    RadioSelected2              Score

1    Project1    3                           1                                       ????

Simplified formular:   Score = (3+1)/2 = 2, now I need to write value 2 to where Score is the  record ID 1.

Thanks

 

Hi,

Can u clarify, do we want to update Score to DB (at serverside)? or just want to show in another field (like textbox) at clientside ?

If it is to updated the db record at server

using (SqlConnection connection = new SqlConnection(MyConString))
            {
                try
                {
                    string cmdText = "Update Project SET Score=@Score WHERE ID=@ID";
                    SqlCommand cmd = new SqlCommand(cmdText, connection);
                    cmd.Parameters.AddWithValue("@Score", calculatedscore);
                    cmd.Parameters.AddWithValue("@ID", recordID);
                    connection.Open();
                    int result = cmd.ExecuteNonQuery();
                   
                }
                catch (Exception ex)
                {

                }
            }

If it is to update the client html table score column, it depends how you are calculate. suppose if you u r calculating by click on the button on same row

$('.buttonclassname').each(function(){
	$(this).click(function(){
		//do the calc
		$(this).siblings('#lblscore').text(calculatedone);
	});
});

I need to write it to the DB, at the server side.

Thanks in advance

As mentioned, I am new and still trying to get the concept of this MVC….

I have the code to calculate the score in edit view just below the radio button sets.

if
(Model.project.LegalID == 1)

{    legalPoint = 3;}

else
if(Model.project.LegalID
== 2)

{ legalPoint = 2; }

else 

.

.

Hope this detail helps

Can you elaborate a bit more… where does your code go? the view??

Hi,

dccmvc

I have the code to calculate the score in edit view just below the radio button sets.

Do u have Razor code to calculate score in Edit View?

Then that doesn’t work, since ur code works only at serverside.

For clientside, u have to use js/jquery and save it in hidden field, so that during postback it can be accessed at serverside actionMethod.

Yes I have Razor code. Can you or someone take step further and provide some code (which will help me a ton)?

I did try this code as below in Edit View but did not write the value to the destination field "legalPoint":

————Radio Buttons—————————————————————————————–

@Html.RadioButtonFor(model => model.project.LegalID,"1",
new
{ onclick =
"LegalInfoChanged(’1′)"
})
<br
/>

@Html.RadioButtonFor(model => model.project.LegalID,"2",
new
{ onclick =
"LegalInfoChanged(’2′)"
})
<br
/>

@Html.RadioButtonFor(model => model.project.LegalID,"2",
new
{ onclick =
"LegalInfoChanged(’2′)"
})
<br
/>

———On
click will call LegalInfoChanged function as below:——————–

<script
type="text/javascript">

function
LegalInfoChanged(mySelection) {

if (mySelection ==
’1′)
{
document.getElementById("project_LegalPoint").val
= 9;
 }

else
if
(mySelection ==
’2′)
{document.getElementById("project_LegalPoint").val
= 18;
}

else {document.getElementById("project_LegalPoint").val
= 27;
}

</script>

"project_LegalPoint"
is the ID of field "LegalPoint"

 

Hi,

Try updating val to value in js and expecting legalPoint is a hiddenfield.

document.getElementById("project_LegalPoint").value
= 9;

Check for errors in browser, if any.

[RESOLVED]Custom Radio Button selected Value in Jquery issue

Hi ,

I am not able to get selected radio button value.

UI rendered code-

When i select radio button,while am seeing UI rendered code,its not updated "checked" property. still its showing the below

<div
class="RadioButton">

<input
Qid="0"
Value="2"
aria-required="true"
data-val="true"
data-val-required="This
field is required."

id="rdo_0"
name="rnm_0"
type="radio"></input>

<label
id=’Name_2′>Item
2
</label>

</div>

<div
class="RadioButton"><input
Qid="0"
Value="2"
aria-required="true"
data-val="true"
data-val-required="This
field is required."

id="rdo_0"
name="rnm_0"
type="radio"></input>

<label
id=’Name_2′>Item
2
</label>

</div>

<div
class="RadioButton"><input
Qid="0"
Value="2"
aria-required="true"
data-val="true"
data-val-required="This
field is required."

id="rdo_0"
name="rnm_0"
type="radio"></input>

<label
id=’Name_2′>Item
2
</label>

</div>

<span>&nbsp;</span>

<span
class="field-validation-valid
errortext"
data-valmsg-for="rnm_0"
data-valmsg-replace="true"></span>

HtmlHelper
class

am using the below html helper method to generate the radio buttons.

 public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
           this HtmlHelper<TModel> htmlHelper,
           Expression<Func<TModel, TProperty>> expression,
           IEnumerable<SelectListItem> listOfValues,string name
            )
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var sb = new StringBuilder();

            if (listOfValues != null)
            {
                // Create a radio button for each item in the list 
                foreach (SelectListItem item in listOfValues)
                {
                    // Generate an id to be given to the radio button field 
                    var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);

                    // Create and populate a radio button using the existing html helpers 
                    var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
                    TagBuilder textBox = new TagBuilder("input");
                    textBox.Attributes.Add("type", "radio");
                    textBox.Attributes.Add("name", "rnm_"+name);
                    textBox.Attributes.Add("id", "rdo_" + name);
                    textBox.Attributes.Add("Qid", name);
                    textBox.Attributes.Add("Value", item.Value);
                   
                        textBox.Attributes.Add("aria-required", "true");
                        textBox.Attributes.Add("data-val", "true");
                        textBox.Attributes.Add("data-val-required", "This field is required.");
                        var radio = textBox.ToString(TagRenderMode.Normal);
                  
                   // var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
                    // Create the html string that will be returned to the client 
                    // e.g. <input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line1</label> 
                    sb.AppendFormat("<div class="RadioButton">{0}{1}</div>", radio, label);
                }
            }

            return MvcHtmlString.Create(sb.ToString());
        }


i have selected Last(3 rd radio button)..How can i get selected value in jquery?

please help me on that.

Thanks,

Sundar.

Hi,

Sundar1987

When i select radio button,while am seeing UI rendered code,its not updated "checked" property. still its showing the below

checked property of radio buttons won’t effect in view-source/ rendered code at browser, it will does in inmemory.

so try using jquery  which can get u the desired result (checked property value).

[RESOLVED]Binding Radio Button in MVC giving Null Exception

Hi,

I am trying to bind Radio Button in MVC. I am new to MVC. Please help me.

In Model class:-

    public class Alert
    {
        public int Id { get; set; }

        public string GetAlert { get; set; }
    }
    public class Member
    {
        public List<Alert> alert { get; set; }
    }

In DataAccess class:-

public List<Alert> RecAlert()
        {
            Alert alert = new Alert();
            List<Alert> list = new List<Alert>();
            con.Open();
            SqlCommand cmd = new SqlCommand("select Id,Alert from tblAlert", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                //Alert al = new Alert();
                alert.Id = Convert.ToInt32(ds.Tables[0].Rows[i]["Id"]);
                alert.GetAlert = ds.Tables[0].Rows[i]["Alert"].ToString();
                list.Add(alert);
            }

            con.Close();
            return list;
        }

In Controller class

        public ActionResult RecAlerts()
        {
            DAO.DataAccess da = new DAO.DataAccess();
            List<Alert> alert = new List<Alert>();
            alert = da.RecAlert();
            return View(alert);
        }

Inside view

@model  MvcApplicationEmpty.Models.Member

@{
    ViewBag.Title = "AddMember";
}

<h2>AddMember</h2>

<table>
    <tr>
        <td style="width: 33%">
            Receive Alerts
        </td>
        <td>
             @Html.RadioButtonFor(m=>m.alert,Model.alert)
        </td>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            <input type="submit" name="btnSubmit" value="Register" />
        </td>
    </tr>
</table>

It is giving below error.

Value cannot be null.
Parameter name: value

Please help
Rahul

Rahul_agg11

@Html.RadioButtonFor(m=>m.alert,Model.alert)

try this

@{
    foreach (var alert in Model.alert)
    { 
        @Html.RadioButton("alert", alert.Id)@alert.GetAlert
    }
}

Hi,

Thanks for replying.

 @{
                foreach (var alert in Model.alert)
                { 
                    @Html.RadioButton("alert", alert.Id)@alert.GetAlert
                }
            }

Its still giving error on foreach statement.

Null Refernce exception was unhandled by user code.

Object reference not set to an instance of an object.

Thanks,

Rahul

Have you tried setting your alert property on a Member object like the one that you are currently using and passing that into your View :

public ActionResult RecAlerts()
{
         DAO.DataAccess da = new DAO.DataAccess();
            
         // Build your model (and populate your List)
         Member model = new Member(){ alert = da.RecAlert() };

         // Pass your model to your View
         return View(model);
}

Additionally, you’ll want to place a breakpoint prior to your return View(model); line above to ensure that your alert property was properly set. If that is the case, then you should be able to use the code you provided above (although to be safe, you
might want to add some null checking in there as well
) :

@if (Model != null && Model.alert != null)
    {
        foreach (var alert in Model.alert)
        {
            @Html.RadioButton("alert", alert.Id) @alert.GetAlert
        }
    }
 

Rahul_agg11

@model MvcApplicationEmpty.Models.Member

since the view expecting the model of type Member.

Rahul_agg11

return View(alert);

But in above statement you are returning List<Alert> to render the view. how come the gets render

The action must return the object(s) of type whatever View is expecting. 

So the action should return something like this

 public ActionResult RecAlerts()
        {
            
            List<Alert> alerts = new List<Alert>();
            for (int i = 1; i <= 10; i++)//get from database
            {
                Alert alert = new Alert();
                alert.Id = i;
                alert.GetAlert = "Alert "+i.ToString();
                alerts.Add(alert);
            }
            Member member = new Member();
            member.alert = alerts;
            return View(member);
        }

You might be able to clean up your existing method that populates your records as well :

public List<Alert> RecAlert()
{
        // Build your list of alerts to return    
        List<Alert> list = new List<Alert>();
       
        // You should consider using a using statement to build your connection here (to avoid memory leaks)
        using(var con = new SqlConnection("Your Connection String"))
        {
               // Open your connection
               con.Open();

               // Build your command (and query)
               using(var cmd = new SqlCommand("SELECT Id, Alert FROM tblAlert", con)) 
               {
                      // Execute your queyry and read through your results
                      using(var reader = cmd.ExecuteReader())
                      {
                             // Read through your rows and build your alerts
                             while(reader.Read())
                             {
                                   // Build an alert
                                   var alert = new Alert();
                                   alert.Id = Convert.ToInt32(reader["Id"]);
                                   alert.GetAlert = reader["Alert"];

                                   // Add this to your list
                                   list.Add(alert);
                             }    
                      }
               }
        }

        // Return your list
        return list;
}

[RESOLVED]Best Way to dynamically add textboxes on radiobutton click in MVC for non-JS users

I have a requirement where i have to dynamically add textboxes based on the radiobutton click i.e if 1 click then add 1 textbox, 2 then 2 & so on upto 6.

With jquery we can easily achieve this. But for non-JS users what should we do.

Any idea what can be a generic solution like a custom HTMLHelper or Partial View.

Hi,

DreamBig

radiobutton click i.e if 1 click then add 1 textbox, 2 then 2 & so on upto 6.

clientside events should be handled only through JS.

DreamBig

Any idea what can be a generic solution like a custom HTMLHelper or Partial View.

above both are serverside logics, which are not useful here.

[RESOLVED]How get the radiobutton selected Value in Controller ?.

Hi Friends,

               How to get the value of radiobutton when we select the One Selection In the Controller . Give me suggestion with real Example 

 

Thanks In Advance ,

Karthik K 

Hi Karthik,

Use below code

<!-- Example of Radio Buttons (notice the name attribute) -->
<input type="radio" name="YourRadioButton" value="A">A<br />
<input type="radio" name="YourRadioButton" value="B">B<br />


[HttpPost]
public ActionResult YourAction()
{
      //Your Action Code Here
}

or

[HttpPost]
public ActionResult YourAction(string YourRadioButton)
{
      var YourRadioButton = Request.Form["YourRadioButton"];
}

Hi PawanPal,

                   Thank you so much .Its coming   

Karthik K

[RESOLVED]Send selected item value to JavaScript from RadioList

I have a radioList and upon checking one of the radio buttons I want to provide js with the selected item in order to do some simple hide and show of panels.

<asp:RadioButtonList id="rdlSource" Name="ListSource" runat="server" RepeatDirection="Horizontal" align="left" onclick="sourceType();">
                   <asp:ListItem Text="Observation/Incident/Event" ></asp:ListItem>
                   <asp:ListItem Text="Self-Assessment"></asp:ListItem>
                  <asp:ListItem Text="Internal Audit"></asp:ListItem>
                  <asp:ListItem Text="External Audit(on CE)"></asp:ListItem>
                  <asp:ListItem Text="Supplier Audit/Surveillance"></asp:ListItem>
                  <asp:ListItem Text="Customer Complaint"></asp:ListItem>
                  <asp:ListItem Text="Other"></asp:ListItem>
                </asp:RadioButtonList>
     function sourceType(){
           
             var source = document.getElementById('<%=rdlSource.ClientID%>');
                alert(source);
</script>

Source is not fetching the correct item and gets the id of the table.
this is what the page source shows me. 

<td colspan="5">
              <table id="MainContent_nestedContent_rdlSource" Name="ListSource" align="left">
	<tr>
		<td><input id="MainContent_nestedContent_rdlSource_0" type="radio" name="ctl00$ctl00$MainContent$nestedContent$rdlSource" value="Observation/Incident/Event" /><label for="MainContent_nestedContent_rdlSource_0">Observation/Incident/Event</label></td><td><input id="MainContent_nestedContent_rdlSource_1" type="radio" name="ctl00$ctl00$MainContent$nestedContent$rdlSource" value="Self-Assessment" /><label for="MainContent_nestedContent_rdlSource_1">Self-Assessment</label></td><td><input id="MainContent_nestedContent_rdlSource_2" type="radio" name="ctl00$ctl00$MainContent$nestedContent$rdlSource" value="Internal Audit" /><label for="MainContent_nestedContent_rdlSource_2">Internal Audit</label></td><td><input id="MainContent_nestedContent_rdlSource_3" type="radio" name="ctl00$ctl00$MainContent$nestedContent$rdlSource" value="External Audit(on CE)" /><label for="MainContent_nestedContent_rdlSource_3">External Audit(on CE)</label></td><td><input id="MainContent_nestedContent_rdlSource_4" type="radio" name="ctl00$ctl00$MainContent$nestedContent$rdlSource" value="Supplier Audit/Surveillance" /><label for="MainContent_nestedContent_rdlSource_4">Supplier Audit/Surveillance</label></td><td><input id="MainContent_nestedContent_rdlSource_5" type="radio" name="ctl00$ctl00$MainContent$nestedContent$rdlSource" value="Customer Complaint" /><label for="MainContent_nestedContent_rdlSource_5">Customer Complaint</label></td><td><input id="MainContent_nestedContent_rdlSource_6" type="radio" name="ctl00$ctl00$MainContent$nestedContent$rdlSource" value="Other" /><label for="MainContent_nestedContent_rdlSource_6">Other</label></td>
	</tr>
</table>

Really confused, i have seen many solutions and none of them have worked out. Please help :) Thank you

You can use Jquery to get the selected value in radiobutton list.

Please try with the below code

 <asp:RadioButtonList ID="rdlSource" Name="ListSource" runat="server" RepeatDirection="Horizontal"
            align="left" onclick="sourceType(this);">
            <asp:ListItem Text="Observation/Incident/Event"></asp:ListItem>
            <asp:ListItem Text="Self-Assessment"></asp:ListItem>
            <asp:ListItem Text="Internal Audit"></asp:ListItem>
            <asp:ListItem Text="External Audit(on CE)"></asp:ListItem>
            <asp:ListItem Text="Supplier Audit/Surveillance"></asp:ListItem>
            <asp:ListItem Text="Customer Complaint"></asp:ListItem>
            <asp:ListItem Text="Other"></asp:ListItem>
        </asp:RadioButtonList>

JQuery Code

 <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
        <script>
            function sourceType(rbl) {
            //Get the selected value from radiobuttonlist
                var selectedvalue = $("#" + rbl.id + " input:radio:checked").val();
                alert(selectedvalue);
            }
        </script>

if you want a pure javascript solution then you can use the below code

<script>

            function sourceType() {
            //Get the Radiobuttonlist object here
                var radioButtons = document.getElementsByName("rdlSource");
                //Loop through all items in radiobuttonlist
                for (var x = 0; x < radioButtons.length; x++) {
                //check if radiobutton is checked or not
                    if (radioButtons[x].checked) {
                    //show the value as alert
                        alert(radioButtons[x].value);
                    }
                }
            }

        </script>
        <asp:RadioButtonList ID="rdlSource" Name="ListSource" runat="server" RepeatDirection="Horizontal"
            align="left" onclick="sourceType();">
            <asp:ListItem Text="Observation/Incident/Event"></asp:ListItem>
            <asp:ListItem Text="Self-Assessment"></asp:ListItem>
            <asp:ListItem Text="Internal Audit"></asp:ListItem>
            <asp:ListItem Text="External Audit(on CE)"></asp:ListItem>
            <asp:ListItem Text="Supplier Audit/Surveillance"></asp:ListItem>
            <asp:ListItem Text="Customer Complaint"></asp:ListItem>
            <asp:ListItem Text="Other"></asp:ListItem>
        </asp:RadioButtonList>

Hello A2H, 
Thank you for your response. I have tried your javascript code and I seem to get the length of 0 for radioButtons.length. 

Hi TheMiniShaq,

Please try to use the following code.

    <script type="text/javascript">
        function sourceType() {
            //Get the Radiobuttonlist object here
            var radioButtons = document.getElementsByName("rdlSource");

            var RadioButtonS = document.getElementsByTagName('input');
            //Loop through all items in radiobuttonlist
            for (var x = 0; x < radioButtons.length; x++) {
                //check if radiobutton is checked or not
                if (radioButtons[x].checked) {
//show the value as alert var lbl = RadioButtonS[x + 1].parentElement.getElementsByTagName('label'); alert(lbl[0].innerHTML); } } } </script> <div> <asp:RadioButtonList ID="rdlSource" Name="ListSource" runat="server" RepeatDirection="Horizontal" align="left" onclick="sourceType();"> <asp:ListItem Text="Observation/Incident/Event" Value="0"></asp:ListItem> <asp:ListItem Text="Self-Assessment" Value="1"></asp:ListItem> <asp:ListItem Text="Internal Audit" Value="2"></asp:ListItem> <asp:ListItem Text="External Audit(on CE)" Value="3"></asp:ListItem> <asp:ListItem Text="Supplier Audit/Surveillance" Value="4"></asp:ListItem> <asp:ListItem Text="Customer Complaint" Value="5"></asp:ListItem> <asp:ListItem Text="Other" Value="6"></asp:ListItem> </asp:RadioButtonList> </div>

Best Regards,
Dillion

TheMiniShaq

Hello A2H, 
Thank you for your response. I have tried your javascript code and I seem to get the length of 0 for radioButtons.length. 

The above code is working fine for me. Looks like the issue is with how we are referring the radiobutton list control as your control is inside a contentplaceholder. Try using the control clientid to refer the radiobutton list

Please try with the below code

 <script>

            function sourceType() {
            //Get the Radiobuttonlist object here
                var radioButtons = document.getElementsByName('<%=rdlSource.ClientID%>');
                //Loop through all items in radiobuttonlist
                for (var x = 0; x < radioButtons.length; x++) {
                //check if radiobutton is checked or not
                    if (radioButtons[x].checked) {
                    //show the value as alert
                        alert(radioButtons[x].value);
                    }
                }
            }

        </script>

[RESOLVED]How to check the element of a control which is inside a grid using javascript

Hi guys,

I have a grid in which  in which first cell is check box 2nd is drop down 3 rd  cell have radio button  and 4th cell have label

Now condition is that if fisrt check box than check if  radio box is checked then value of selected item from drop down should get appended with 

the label which is in 4th cell.

How to do it 

You can try with the below implemenation

HTML:

<asp:UpdatePanel runat="server">
            <ContentTemplate>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowSorting="True"
                    DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_OnRowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
                                    DataTextField="AddressLine1" DataValueField="AddressLine1">
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:RadioButton ID="RadioButton1" runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorks2008R2ConnectionString %>"
                    SelectCommand="SELECT top 20  [AddressID], [AddressLine1] FROM Person.Address">
                </asp:SqlDataSource>
            </ContentTemplate>
        </asp:UpdatePanel>

C#:

/// <summary>
        /// Handles the CheckedChanged event of the CheckBox2 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
        {
            //Get the checkbox from sender object
            CheckBox chk = sender as CheckBox;
            //Get the selected row from checkbox container
            GridViewRow row = (GridViewRow)chk.NamingContainer;
            //Get the dropdownlist control from selected GridViewrow
            DropDownList drpdwctrl = row.FindControl("DropDownList1") as DropDownList;
            //Get the Radiobutton control from selected GridViewrow
            RadioButton rdpbtnctrl = row.FindControl("RadioButton1") as RadioButton;
            //Get the label control from selected GridViewrow
            Label lblctrl = row.FindControl("Label3") as Label;
            //Check if checkbox is checked or not
            if (chk.Checked)
            {
                //Check if Radiobutton control is checked or not
                if (rdpbtnctrl.Checked)
                {
                    //Assign the value to existing text in label control
                    lblctrl.Text = lblctrl.Text + " " + drpdwctrl.SelectedItem.Text;
                }
            }

        }

Change the ids of control as per your gridview

Rendered Output

EDIT:Added Rendred output demo

Hi kaushiklotus,

Thanks for your post.

Based on your requirement, I create a sample for you, you could refer to it and make some changes according to your specific requirements.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../../../Scripts/jquery-1.8.2.js"></script>
    <script>
        $(function () {
            $(":checkbox").change(function () {
                var ischecked = $(this).is(":checked");
                var rd = $(this).parent().siblings().find(":radio").is(":checked");

                if (ischecked && rd) {
                    var mes = $(this).parent().siblings().find("select").find("option:selected").val();
                    //alert(mes);
                    $(this).parent().siblings().find("span").html(mes);
                }
            });

            $(":radio").change(function () {
                var ischecked = $(this).is(":checked");
                var rd = $(this).parent().siblings().find(":checkbox").is(":checked");

                if (ischecked && rd) {
                    var mes = $(this).parent().siblings().find("select").find("option:selected").val();
                    //alert(mes);
                    $(this).parent().siblings().find("span").html(mes);
                }
            });

            $("select").change(function () {
                var mes = $(this).find("option:selected").val();
                var ischecked = $(this).parent().siblings().find(":checkbox").is(":checked");
                var rd = $(this).parent().siblings().find(":radio").is(":checked");

                if (ischecked && rd) {
                    $(this).parent().siblings().find("span").html(mes);
                }
            });
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:CheckBox ID="CheckBox1" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
                                DataTextField="Name" DataValueField="Name">
                            </asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:RadioButton ID="RadioButton1" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [ChartInfo]"></asp:SqlDataSource>
        </div>
    </form>
</body>
</html> 

In above sample code, I use some selectors and events, if you’d like to learn about these, you could check the following links.

If you have any question about my reply, please let me know freely.

Best Regards,

Fei Han

Thank you 

Hi kaushiklotus.

Have you tried my sample? your requirement is that checking the elements inside a gridview using javascript, does my sample not meet your requirement?

Best Regards,

Fei Han