1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2002
    Rep Power

    Accessing form values using javascript

    I want to be able to set a cookie on a group of radio buttons, but I can't seem to get the value of the selected radio button. Here is what I'm trying to do...

    seatType = document."formname"."radiogroupname".value

    then when I try to do an alert(seatType), I get "undefined" rather than a 1,2,3, or 4 which is what I'm trying to get.

    each radio button has the name set to "seatType", and the value is a number.

    ... so what am I doing wrong? This will work for text boxes, but not for my radio buttons
  2. #2
  3. No Profile Picture
    Senior Citizen
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Jan 2001
    Rep Power
    <script type="text/javascript" language="javascript">

    function getRadio(f, grpName) {
    var grp, rad, r = 0;
    grp = (typeof grpName == 'string') ? f[grpName] : grpName;
    while (rad = grp[r++]) if (rad.checked) return rad.value;
    return '';

    <input type="radio" name="seatType" value="1"> 1<br>
    <input type="radio" name="seatType" value="2"> 2<br>
    <input type="radio" name="seatType" value="3"> 3<br>
    <input type="radio" name="seatType" value="4"> 4<br><br>
    <input type="text" name="readout" size="12">
    <input type="button" value="Get Radio"
    onclick="x=getRadio(this.form,'seatType');if(x)readout.value='Seat Type: '+x">
    <input type="reset">

    Groups of radios generate an array, stored at form_ref.radio_group_name; since it's an array, you'll need to rummage through it, getting pointers to the actual Radio objects, and reading their .checked property. Common problem. The above also accepts the group name as a variable: getRadio(this.form,seatType).

    cheers, adios
    Last edited by adios; October 24th, 2002 at 08:18 PM.

IMN logo majestic logo threadwatch logo seochat tools logo