0

I am generating multiple buttons using PHP:

<form name="submit_form" id="submit_form" action="">

<?php
for ($i = 0; $i < count($value); $i++) {?>
<input type="radio" name="answer" value="<?php echo $value[$i]; ?>"/>$value[$i]<?php }?>
</form>

I have problem checking if radio button is selected using Javascript since it keeps returning 'undefined'

I am accessing radio buttons (before ) using javascript in this way:

    alert(document.forms["submit_form"].elements["answer"].checked);

I have tried echoing whole html, same thing happens...

3 Answers3

1

Use document.getElementsByName(name); - This method return a nodeList.

list=document.getElementsByName("answer");

alert(list.item(0).checked); //1st 
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
0

Use Jquery....

To get the value of the selected radioName item of a form called 'myForm':

$('input[name=radioName]:checked', '#myForm').val()

How can I know which radio button is selected via jQuery?

Community
  • 1
  • 1
Boone
  • 1,046
  • 1
  • 12
  • 30
  • Or better: [Don't](http://www.developer.nokia.com/Community/Discussion/showthread.php?198014) [use](http://www.artefactgroup.com/#/content/want-a-faster-html5-webapp-dont-use-jquery/) [jQuery](http://julien.richard-foy.fr/blog/2011/10/22/don-t-use-jquery-to-write-a-web-application-part-1/) (at least for simple things) – Bergi Nov 28 '11 at 03:51
  • Yes, I was trying to avoid jQuery. Thanks for answer –  Nov 28 '11 at 09:09
0

document.getElementsByTagName("answer") and your document.forms-approach both return an array (correct: a NodeList) of <input> elements. You will have to loop through them and check each for the checked property.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375