-2

I have multiple radio buttons with same name attribute for my real estate website(e.g. 1room 2rooms 3rooms) for filtering purposes.

The thing I realize is that my code is very anti-DRY and it seems very repetitive.

I tried :

if (document.getElementById('rooms-all').checked) {
    filters.rooms = 999999999;
} else if (document.getElementById('room-1').checked) {
    filters.rooms = 1;
} else if (document.getElementById('room-2').checked) {
    filters.rooms = 2;
} else if (document.getElementById('room-3').checked) {
    filters.rooms = 3;
} else if (document.getElementById('room-4').checked) {
    filters.rooms = 4;
} else if (document.getElementById('room-5').checked) {
    filters.rooms = 5;
}

This works just great, but I wanted to do something like :

let x = document.getElementsByName('rooms').checked; // also tried .value
console.log(x)

but for some reason it returns undefined

My HTML looks like

<input type="radio" id="rooms-all" class='radio' name="rooms" value="999999999" checked>
<label for="rooms-all">All</label>
<input type="radio" id="room-1" class='radio' name="rooms" value="1">
<label for="room-1">1 Room</label>
<input type="radio" id="room-2" class='radio' name="rooms" value="2">
<label for="room-2">2 Rooms</label>
<input type="radio" id="room-3" class='radio' name="rooms" value="3">
<label for="room-3">3 Rooms</label>
<input type="radio" id="room-4" class='radio' name="rooms" value="4">
<label for="room-4">4 Rooms</label>
<input type="radio" id="room-5" class='radio' name="rooms" value="5">
<label for="room-5">5 Rooms</label>

And what I see currently that I don't use the values I gave them at all.

What is the better way of doing it?

Mamun
  • 66,969
  • 9
  • 47
  • 59
Berin Aptula
  • 234
  • 1
  • 12
  • 1
    “Some reason” is that getElementsByName returns a node list, and you are now checking if that node list has a `checked` property set, which of course it doesn’t. Using this method, you would still need to loop over the list, and see if the property is set for any of the elements on it, individually. – 04FS Oct 29 '19 at 12:02
  • Check answers like this one in the mentioned duplicate, https://stackoverflow.com/a/47391907/10955263, for a quicker way to get the value of the checked radio button in a group. – 04FS Oct 29 '19 at 12:04

7 Answers7

1

getElementsByName returns a node list object so, you can iterate through it like you do an array to check like so:

   let x = document.getElementsByName('rooms'); 
    for (var i = 0; i < x.length; i++) {
        var checked = x[i].checked;
        console.log(checked)
    }
Cuong Nguyen
  • 314
  • 2
  • 8
  • Even though technically possible, there is absolutely no need to iterate through arrays to get the value of a radio button. If I were you I'd remove this answer, because it isn't useful. – Armen Michaeli Oct 29 '19 at 12:08
  • I agree that this is not the best way to check, wanted to answer his question of why it was returning undefined. – Cuong Nguyen Oct 29 '19 at 12:12
  • 1
    `getElementsByName()` returns a "live node list", which is an "array-like" object, but not an actual array. – Scott Marcus Oct 29 '19 at 12:15
  • `for (var el of document.getElementsByName('rooms'))` – Unihedron Nov 01 '19 at 11:46
1

A possible solution:

[...document.querySelectorAll('[id^="room"]')]
    .filter(input => input.checked).map(input => Number(input.value))[0];
tcconstantin
  • 369
  • 1
  • 4
1

When you use, document.getElementsByName('rooms') you will get a NodeList which is an array of all Radio buttons. So using .checked on this array wouldn't return anything.

So instead, you can use it like this:

let x = document.getElementsByName('rooms')
 x.forEach((item, index) => {
    if (item.checked){
        filters.rooms = item.value
    }
 })

Or, you can wrap it in a function and add an Event Listener on all your radio buttons like this:

var x = document.getElementsByName('rooms')
var handler = function() {

     x.forEach((item, index) => {
        if (item.checked){
            filters.rooms = item.value
        }
     })
}

x.forEach((item) => { item.onclick = handler})
Mudassir
  • 1,442
  • 11
  • 15
0

get checked:

let x = [ ...document.getElementsByName('rooms')].filter(item => item.checked)[0]; 

let x = [ ...document.getElementsByName('rooms')].filter(item => item.checked)[0]; 

var filters = {rooms: x.value};

function setRoom(e){
  filters.room = e.value;
  x = e;
  console.log("selected value: ", filters.room)
  console.log("selected element: ", x)

}
<input type="radio" id="rooms-all" class='radio' name="rooms" value="999999999"  onchange="setRoom(this)" checked>
<label for="rooms-all">All</label>

<input type="radio" id="room-1" class='radio' name="rooms" value="1" onchange="setRoom(this)">
<label for="room-1">1 Room</label>

<input type="radio" id="room-2" class='radio' name="rooms" value="2" onchange="setRoom(this)">
<label for="room-2">2 Rooms</label>

<input type="radio" id="room-3" class='radio' name="rooms" value="3" onchange="setRoom(this)">
<label for="room-3">3 Rooms</label>

<input type="radio" id="room-4" class='radio' name="rooms" value="4" onchange="setRoom(this)">
<label for="room-4">4 Rooms</label>

<input type="radio" id="room-5" class='radio' name="rooms" value="5" onchange="setRoom(this)">
<label for="room-5">5 Rooms</label>
Bahador Raghibizadeh
  • 1,155
  • 11
  • 23
0

hey you can do like this, var ele = document.getElementsByName('rooms');

        for(i = 0; i < ele.length; i++) { 
            if(ele[i].checked) 
            document.getElementById("result").innerHTML = ele[i].value; 
        } 
mohit dutt
  • 43
  • 3
0

The easiest solution was :

let value =  document.querySelector('input[name="rooms"]:checked').value;

Thank you all for answering!

Berin Aptula
  • 234
  • 1
  • 12
-1

Tryout this adding into your Js file

    $(document).on("click", ".radio", function(event)
  {
            $(this).prop("checked", true); 
             var value = $(this).val( );
            alert(value);
        });
Kaleemullah
  • 446
  • 3
  • 8