简体   繁体   中英

Radio Button list selected items value in javascript

I am using following code to get the selected elements value in radio button list.

function SelectRadioButton()
{
   var radiobutton = document.getElementsByName('<%=RadioButtonList1.ClientID %>');
   alert(radiobutton.length);
for(var x = 0; x < radiobutton.length; x++)
            {
                if(radiobutton[x].checked)
                {
                    alert('selected is ' + radiobutton[x].id);
                }
             }
 }

Following is the HTML markup

  <table id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1" class="chk" onclick="javascript:SelectRadioButton(this, ctl00_ContentPlaceHolder1_idControl_RadioButtonList1)" border="0">
    <tr>
        <td><input id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_0" type="radio" name="ctl00$ContentPlaceHolder1$idControl$RadioButtonList1" value="1" checked="checked" /><label for="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_0">List</label></td><td><input id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_1" type="radio" name="ctl00$ContentPlaceHolder1$idControl$RadioButtonList1" value="2" /><label for="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_1">Assignment</label>

But I am getting length 0 in alert(radiobutton.length); statement. Why is this happening. any thing that I am missing?

You can use jquery to do this.

 alert($(".chk").find("input:checked").length); // chk is your css class name applied to Checkbox List element.

You can get specific element by using this

alert($(".chk").find("input:checked")[0]);

RadioButtonList1 will be converted to radio buttons with ids having RadioButtonList1 , You can iterate through DOM and look for matched ids and put them in some array or directly perform what you want to them.

radiobutton = [];

for(i=0;i<document.forms[0].length;i++)
{
    e=document.forms[0].elements[i];
    if (e.id.indexOf("RadioButtonList1") != -1 )
    {
           radiobutton.push(e); 

    }       
}   

Here's how you do it with javascript only, if you don't want to use getElementById


Code | JSFiddle

function SelectRadioButton(){
    var radiolist = getElementsByClass("table", "chk")[0],
        radios = radiolist.getElementsByTagName("input");

    for(var i = 0; i < radios.length; i++){
        if(radios[i].checked){
            alert('Selected radiobutton is ' + radios[i].id);
        }
    }
 }

function getElementsByClass(tag, name){
    var elements = document.getElementsByTagName(tag);
    var ret = [];

    for(var i = 0; i < elements.length; i++){
        if(elements[i].className.indexOf(name) !== -1){
            ret.push(elements[i]);
        }
    }

    return ret;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM