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

    Join Date
    Jan 2013
    Posts
    85
    Rep Power
    0

    Get value of checked radio buttons


    Hello,
    I have a script that outputs the html for the radio buttons like this:

    <input type="radio" value="1" name="elegirparadalist" class="elegirparadalist">
    <input type="radio" value="2" name="elegirparadalist" class="elegirparadalist">
    <input type="radio" value="3" name="elegirparadalist" class="elegirparadalist">
    <input type="radio" value="4" name="elegirparadalist" class="elegirparadalist">

    I need to get the value of checked radio button, however below script only works when I select the first radio button:

    <script>
    var element2 = document.querySelector('input[name="elegirparadalist"]');
    element2.addEventListener('click', () => {
    console.log(document.querySelector('input[name="elegirparadalist"]').value)
    })
    </script>

    Any help please, thanks
  2. #2
  3. Headless Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,977
    Rep Power
    9647
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2019
    Posts
    2
    Rep Power
    0
    This line of code
    var element2 = document.querySelector('input[name="elegirparadalist"]');
    Is supposed to be
    var element2 = document.querySelectorAll('input[name="elegirparadalist"]');

    Notice the .querySelectorAll
  6. #4
  7. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,134
    Rep Power
    4310
    Originally Posted by RyanLincoln
    Notice the .querySelectorAll
    You could do that, but then you would need to loop through them. By using what requinix suggested, you can avoid that:

    Code:
    document.querySelector('input[name="elegirparadalist"]:checked');
    Spreading knowledge, one newbie at a time.

    Learn CSS. | PHP includes | HTML Validator | CSS validator

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).

IMN logo majestic logo threadwatch logo seochat tools logo