0

All of these radio buttons have an onclick method in which I am trying to get the value of the selected radio button.

<div id="interior">
<label><input type="radio" name="groundfloordropdown" value="125">1BHK</label>
<label><input type="radio" name="groundfloordropdown" value="175">2BHK</label>
<label><input type="radio" name="groundfloordropdown" value="225">3HK</label>
</div>
4b0
  • 21,981
  • 30
  • 95
  • 142
Madhu
  • 75
  • 7

3 Answers3

2

You can use JQuery to get the value by
let value = $('input[name="groundfloordropdown"]:checked').val().

Linh Phan
  • 21
  • 1
  • sorry for the wrong tag, i edited it, i wanted vanilla javascript – Madhu Jan 15 '21 at 07:36
  • 1
    @Madhu, sorry, my bad, this can be converted to `let value = document.querySelector('input[name="groundfloordropdown"]:checked').value`. It will give you the same result – Linh Phan Jan 15 '21 at 07:54
  • thanks a lot this worked out best for me better than all other answers – Madhu Jan 22 '21 at 06:45
  • @LinhPhan you should [edit] your answer to include the vanilla JS version – Phil Apr 26 '22 at 03:46
1
  var names = document.getElementsByName("groundfloordropdown");
   groundfloordropdown.forEach((ground) => {
                if (ground.checked) {
                    alert(`Choise: ${ground.value}`);
                }
            })

this is a pure js have a good day :)

1

Do not declare js events inside tags. This will lead to many bad consequences.

I made you a little javascript code using the forEach() method. This method is required to work with the collection. Namely, when you work with many elements that have the same class, or it will be the same tag.

Also, in this example you get the value of the input tag and the label tag.

If you have any questions, let me know. I will answer with pleasure.

let radio = document.querySelectorAll('.radiogroup input');
let label = document.querySelectorAll('.radiogroup label');

radio.forEach(function (radio_current, index) {
    radio_current.addEventListener('change', function () {
        console.log('Value Radio: ' + this.value + '; Value Label: ' + label[index].innerText);
    });
});
<div class="radiogroup">
  <label><input type="radio" name="groundfloordropdown" value="125">1BHK</label>
  <label><input type="radio" name="groundfloordropdown" value="175">2BHK</label>
  <label><input type="radio" name="groundfloordropdown" value="225">3HK</label>
</div>
s.kuznetsov
  • 14,870
  • 3
  • 10
  • 25