How to Get Checked Radio In Array using Java script in php my code attached?

i am trying to get checked radio "id" and "name" as my radio name and id are same like 1,2,3... and so on

my code is here,

var selection=new Array(); 
 var allR = document.getElementsByTagName('input');
  var a=0;
  var b=0;
    for(var i=0; i<allR.length; i++){ 
        if(allR[i].type=='radio') { b++; }      
        if(allR[i].type=='radio' && allR[i].checked) { a++; } 
    }
var num=0;
alert(b);

for(var j=1;j<=b ;j++) {

  //for(var i=0; i<alr.length; i++){ 

    if(document.getElementsByName('j').checked) {
      selection[num]=j;
      num++;
      alert(j);
  //}
  }
}

in this code var "b" is the number of radio counts and in second loop i am trying to get checked radio in array and printing them too but it just print the total radio button but do not print checked radio ???

hopes for your suggestions

Answers


You should change

if(document.getElementsByName('j').checked)

to

if(document.getElementsByName(j)[0].checked)

as your control has name as 1, 2 , 3. not 'j', and j is your for loop initial, so it not need to be enclosed in single quotes.

as document.getElementsByName returns a collection. you should check element by 0 index.


Just a comment.

the block inside the first for loop can be:

for (var i=0; i<allR.length; i++){ 

    if (allR[i].type=='radio') {
       b++;  
       a += allR[i].checked; 
    }
}

but there are those who dislike depending on type conversion like that.


Need Your Help

Putting all methods in class definition

c++ inline pimpl-idiom

When I use the pimpl idiom, is it a good idea to put all the methods definitions inside the class definition? For example:

Having images as background of JPanel

java swing background jpanel paintcomponent

I am new in Java and I am currently creating a game with graphics. I have this class that extends from JFrame. In this class, I have many JPanels that needs an image as background. As I know, to be...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.