简体   繁体   中英

Javascript, radio buttons and PHP

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...

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

list=document.getElementsByName("answer");

alert(list.item(0).checked); //1st 

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM