SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    286
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    onClick: how to get the value of radio button??

    I have three radio buttons in my form.

    How can I get the value of selected radio button.
    [COLOR=SlateGray]
    Web Developer @ VeriQual

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,097
    Mentioned
    153 Post(s)
    Tagged
    3 Thread(s)
    Code:
    <input type="radio" id="myRadio1" value="1" name="some_name" />
    <input type="radio" id="myRadio2" value="2" name="some_name" />
    <input type="radio" id="myRadio3" value="3" name="some_name" />
    Code JavaScript:
    var value = false;
    if (document.getElementById('myRadio1').checked) {
       value = document.getElementById('myRadio1').value;
    } else if (document.getElementById('myRadio2').checked) {
       value = document.getElementById('myRadio2').value;
    } else if (document.getElementById('myRadio3').checked) {
       value = document.getElementById('myRadio3').value;
    }
     
    if (value !== false) {
       alert('Value of selected radio is ' + value);
    } else {
       alert('Please select an option');
    }

    Please be careful to use !== and not !=
    !== says that the value should not have the same value as false, and that it should be of the same type (boolean).
    if you use != and one of the values is -1, the script goes wrong.
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy


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
  •