SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Addict Phil-man's Avatar
    Join Date
    Nov 2000
    0 Post(s)
    0 Thread(s)
    Hi. I need to know how to use Javascript to test if any one of a series of radio buttons has been checked. There's a catch, though: The radio buttons and their values are dynamically generated out of a database, so there's no way of knowing ahead of time how many radio buttons there will be or what the value associated with each button will be. Thus, I can't simply test the value of each button separately, nor can I use an array unless I can figure out how to count how many options there are when the page is dynamically generated. It seems like there should be any easy way! Thanks in advance.

  2. #2
    SitePoint Guru Vincent Puglia's Avatar
    Join Date
    Feb 2000
    where the World once stood
    0 Post(s)
    0 Thread(s)
    Hi Phil-man and welcome to the sitepoint section where the user's machine does the work

    I see you already realize radio buttons are maintained internally as arrays. I presume you also know that forms are also and that their field elements have the following attributes: name and type.

    That said, here's an off-the-top possible solution:

    function chkIt(formObj)
    with (formObj)
    for (i = 0 ; i < length ; i++)
    if (elements[ i ].type == 'radio')
    for (j = 0; j < elements[ i ].length; j++)
    if (elements[i][j].checked)
    theVal = elements[ i ][j].value;

    1)the with() method is a lazy coder's dream. It tells the browser that any questionable DOM elements that follow should be prefaced with the DOM in the parentheses (in this case, formObj -- document.formname, eg.)
    2) Because of with(), length means formObj.length; elements = formObj.elements
    3) If you have more than one group of radio buttons, you will have to add an additional conditional -- one that checks the radio group's name -- eg: if (elements[i].name = "Group1Buttons")

    Edit Note: I had to edit the response to add spaces in the code "[ i ]" so that the bulletin software doesn't mistaken it for italics.

    Hope this helps. If not, let me/us know and I/we will see what can be done.


    [Edited by Vincent Puglia on 11-09-2000 at 12:25 PM]
    Where the World Once Stood
    the blades of grass
    cut me still


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts