-1

I have 6 inputs in my HTML like this:

 <input type="radio" value="1" />
 <input type="radio" value="2" />
 <input type="radio" value="3" />
 <input type="radio" value="4" />
 <input type="radio" value="5" />
 <input type="submit" onClick="myFunction();" value="submit" />

When the submit button is clicked, a Javascript function is called. In this javascript function, I want to check which of the radio buttons is checked and which aren't.

Thanks in advance!

Martijn
  • 514
  • 6
  • 12

3 Answers3

2

javascript

function myFunction() {
  var x = document.getElementsByTagName("input");
  for(i = 0; i < x.length; i++ ) {
    if(x[i].type = "radio") {
        if(x[i].checked) {
            alert(x[i].value);
        }
    }
  }
}
elti musa
  • 710
  • 2
  • 7
  • 14
1

you can do it easily by jquery

 function myfunction(){
   $("input[type=radio]:checked").each(function(){

  //do something here


   });
    }
A.B
  • 20,110
  • 3
  • 37
  • 71
  • 1
    Why not use a psuedo-selector instead of iterating over all elements? – Tristan Lee Oct 22 '14 at 20:29
  • 1
    edited, actually question was not clear, i thought persons wants to do somethingfor both cases if checked or if not – A.B Oct 22 '14 at 20:31
  • Good point. I just re-read it myself. :) Therefore your original solution may be more appropriate here. It just depends on if these radios are of the same group or not. – Tristan Lee Oct 22 '14 at 20:32
  • hmm, that i have removed now, lets hope it helps the user – A.B Oct 22 '14 at 20:34
-2

You need to add a class first. this will ensure that you are not checking other radio elements in your page. See below.

<input type="radio" value="1" class='radio'/>
<input type="radio" value="2" class='radio'/>
<input type="radio" value="3" class='radio'/>
<input type="radio" value="4" class='radio'/>
<input type="radio" value="5" class='radio'/>
<input type="submit" onClick="myFunction();" value="submit" />

<!-- javascript- add script tags -->

function myFunction() {

    $('.radio').each(function() {

        if($(this).is(':checked')) { 
            alert("it's checked"); 
        }

    })

}
Abhishek Saha
  • 2,564
  • 1
  • 19
  • 29