0

I got my radio Selector that looks like this

<div id="graph_selector" style="display:none; text-align: center;" >
   <p><b>Tipo de Grafico: </b></p>
     <div class="cc-selector">
        <input id="axes" type="radio" name="sel_graph" class="radio_selector" value="axes" />
        <label class="drinkcard-cc axes"for="axes"></label>
        <input id="activity" type="radio" name="sel_graph" class="radio_selector" value="activity" />
        <label class="drinkcard-cc activity" for="activity"></label>
        <input id="pie" type="radio" name="sel_graph" class="radio_selector" value="pie" />
        <label class="drinkcard-cc pie" for="pie"></label>
     </div>
</div>

A button to submit my selection

<button type="submit" class="btn btn-success" id="guardar_grafico">Graficar</button>

Im trying to get the right value on my js but when I use console.log(); all I get is the value from the 1st input= "axes" regardless of what I choose

<script type="text/javascript">    
$('#guardar_grafico').click(function() {
       var graph_selector = document.querySelector('input[name=sel_graph]').value
       console.log(graph_selector);
});

Any help would be appreciated

Chris G
  • 1,598
  • 1
  • 6
  • 18

2 Answers2

0

In order to get the value of the selected radio in a radio group, you need to look for the checked property on each radio.

In this example, it loops through all of the radios with that name="sel_graph" attribute, and filters that list to the 1 radio that is checked.

var graph_selector = Array.from(
    document.querySelectorAll('input[name=sel_graph]')
).filter(radio => radio.checked)[0]?.value;
console.log(graph_selector);

Also, I just realized you're using jQuery. There's a simpler solution with that, check this answer.

jQuery get value of selected radio button

0

nvm, solved the issue, I was missing the checked property on my js

it went from this

var graph_selector = document.querySelector('input[name=sel_graph]').value

to this

var graph_selector = document.querySelector('input[name=sel_graph]:checked').value
Chris G
  • 1,598
  • 1
  • 6
  • 18