-1

I wonder if anyone can help me out, I'm stuck where I need to write a little code that goes like this.

Question : did you like the training?

<input type="radio" name="q4" value="Yes">Yes
<input type="radio" name="q4" value="No">No

whatever is checked I want to pass it to a javascript variable.

dfsq
  • 191,768
  • 25
  • 236
  • 258
Rayan Sp
  • 1,002
  • 7
  • 17
  • 29

2 Answers2

5

You can try this using Jquery.

$('input[name="q4"]:checked').val();
Sachin
  • 40,216
  • 7
  • 90
  • 102
  • 3
    Since the question is not tagged as `jquery`, you should provide an alternative solution (without jQuery) as well. – Felix Kling Mar 24 '13 at 15:46
  • can you tell me how to write this in Javascript? or how can I define in jQuery, example answer = $('input[name="q4"]:checked').val(); << is it correct? – Rayan Sp Mar 24 '13 at 15:51
3

I think you could do something like this:

var ch = document.getElementsByName('q4');

for (var i = ch.length; i--;) {
    ch[i].onchange = function() {
        alert(this.value);
    }
}

http://jsfiddle.net/EUErP/

So you subscribe to to change event and can use selected value somehow.

Alternatively you can use querySelector (querySelectorAll) methods. Here is an example of how you can get checked element value:

var checked = document.querySelector('[name="q4"]:checked');

http://jsfiddle.net/EUErP/2/

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • its giving me null, any suggestion? what I did is I used querySelector just like u suggested before with this code Yes No – Rayan Sp Mar 24 '13 at 16:10
  • Maybe nothing is checked? – dfsq Mar 24 '13 at 16:11
  • I managed to make it work after all, but it seems that it's not compatible with IE as I'm getting error object doesn't support this property or method, it refers to this line ' var checked = document.querySelector('[name="answer1"]:checked'); ' – Rayan Sp Mar 24 '13 at 16:55
  • `querySelector` is available in IE8+. Check support http://caniuse.com/#feat=queryselector – dfsq Mar 24 '13 at 18:14
  • the version I use is IE7 – Rayan Sp Mar 24 '13 at 18:17
  • If you need to support IE7 you can use this approach http://jsfiddle.net/EUErP/8/ – dfsq Mar 24 '13 at 18:19