nad nad - 1 month ago 17
ASP.NET (C#) Question

Get Checkboxlist selected Item using javascript not working

I have selected 2 items from the

checkboxlist
with below code which I tried I am getting error as


attributes is not defined.


Here is my code

var checkboxlist = document.getElementById('<%= ddlStatus.ClientID %>');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('span');

for(i = 0; i < checkOptions.length; i++)
{
if(checkOptions[i].checked)
{
alert(listSelected[i].attributes["STATUS"].value);
}
}


kindly let me know how to get the selected value

UPDATE

Fiddle of the checkboxlist with 2 items selected

JSFiddle

Answer

first of all, in your JSFiddle you're checkbox titles are in label not span so change this line:

var listSelected = checkboxlist.getElementsByTagName('span');

to:

var listSelected = checkboxlist.getElementsByTagName('label');

apart from that, you don't have an attribute called "STATUS" on those labels, I've updated your fiddle - see here https://jsfiddle.net/Lg8w2u7d/2/

UPDATE

final code that gets last selected value, with compatibility to IE8

 var checkboxlist = document.getElementById('ddlStatus');
 var checkOptions =   checkboxlist.getElementsByTagName('input');
 var listSelected = checkboxlist.getElementsByTagName('label');
 var last_val = '';
 for(i = 0; i < checkOptions.length; i++)
        {
            if(checkOptions[i].checked)
            {
                last_val = listSelected[i].textContent || listSelected[i].innerText; // so it works in IE8 and lower
            }
        }
 alert(last_val);