SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru
    Join Date
    Oct 2006
    Location
    Queensland, Australia
    Posts
    852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Checking if Radio Button is Selected

    How do I check if a radio button is selected or not, for example, if the page loads with the radio button selected, then I want to perform a task. I also want to perform the same task if the radio button is selected after the page is loaded.

    I'm no javascript pro, so don't get too technical with me

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Code Javascript:
    function checkRadio() {
      var radio1 = document.getElementById('radio1');
      if (radio1.checked) {
        // do stuff for when radio1 is selected
      }
      else {
        // do something else
      }
    }
     
    window.onload = checkRadio;
    That will check if your radio button with the ID "radio1" is checked when the page loads. Naturally you don't have to access it via its ID, you could access it via its name if you wanted to.

  3. #3
    SitePoint Guru
    Join Date
    Oct 2006
    Location
    Queensland, Australia
    Posts
    852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for that. I imagine I'd call that function directly after my radio button. I'll also include an onchange or onclick event which will also trigger it, that way it should work both on load, and when the user plays around with the radio buttons.

    Cheers!

  4. #4
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    If by this:
    I'd call that function directly after my radio button
    you mean you'd put it in script tags right after your radio button, DON'T.

    That javascript should go in the <head>. Then do the same sort of thing with your onchange or onclick events. You'd need to do something like this:
    Code Javascript:
    function init() {
      var radio1 = document.getElementById('radio1'), radio2 = document.getElementById('radio2');
      checkRadio.call(radio1); // happens onload
      radio2.onclick = checkRadio;
      radio1.onchange = checkRadio;
    }
    function checkRadio() {
      if (this.checked) {
        // do stuff for when rad is selected
      }
      else {
        // do something else
      }
    }
     
    window.onload = init;
    call(), if you've never seen it before, just makes checkRadio be called with this as the first parameter of call().


Bookmarks

Posting Permissions

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