|
|||||||
| JavaScript JavaScript (not Java) Discussion and technical support, including AJAX and frameworks (JQuery, MooTools, Prototype...) |
![]() |
|
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Getting the value of selected radio buttons
Hi,
I have a bit of a tricky question here, i have several radio button groups in my form. They share the same name 'ptag' as i am storing them in a PHP variable eg. Code:
<input type="radio" name="ptag[group1]" value="g1a" /> <input type="radio" name="ptag[group1]" value="g1b" /> <input type="radio" name="ptag[group2]" value="g2a" /> <input type="radio" name="ptag[group2]" value="g2b" /> <input type="radio" name="ptag[group3]" value="g3a" /> <input type="radio" name="ptag[group3]" value="g3b" /> I have attempted some code below, and while i don't get any JS errors, i'm also getting no value passed, i suspect i am not retrieving the value correctly, any ideas on how i could rework the code below to get the values of selected radio buttons. Code:
<script type="text/javascript">
function get_radio_value()
{
for (var i=0; i < document.filterform.ptag.length; i++)
{
if (document.filterform.ptag[i].checked)
{
var rad_val = document.filterform.ptag[i].value;
var somediv = document.getElementById('someid');
somediv.innerHTML = document.filterform.ptag[i].value;
}
}
}
</script>
|
|
#2
|
||||
|
||||
|
In javascript the value of an attribute is a string, thus "ptag[group1]" does not substitute an array so that the special characters "[]" have no special meaning. It's just a simple string, same as "foo", "fee0011" or "blah[_98i[[".
That means you have 3 independent radio groups and there is no "natural" way to refer them as a "global" group. To do that, you should work a little bit on the code, using a RegExp match and an array to capture the values. Could be something like this: Code:
function get_radio_value(){
var rads=document.getElementsByTagName('input'), i=0, val=[], r;
while(r=rads[i++]){
if(r.type=='radio'&&r.name.match(/ptag/g)&&r.checked){
val[val.length]=r.value;
}
}
//now the values of the checked radios are "captured" into the array called val
document.getElementById('someid').innerHTML=val.join(',');
}
Last edited by Kor; 11-08-2009 at 03:04 AM. |
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|