JavaScript select radio button based on value code example

Example 1: get radio button value javascript

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

Example 2: which radio button is selected javascript

$('#myForm input').on('change', function() {
   alert($('input[name=radioName]:checked', '#myForm').val()); 
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="myForm">
  <input type="radio" name="radioName" value="1" /> 1 <br />
  <input type="radio" name="radioName" value="2" /> 2 <br />
  <input type="radio" name="radioName" value="3" /> 3 <br />
</form>

Example 3: getting value from radio button javascript

var elements = document.getElementsByName('radioButton');
    var checkedButton;
    console.log(elements);
    elements.forEach(e => {
        if (e.checked) {
            //if radio button is checked, set sort style
            checkedButton = e.value;
        }
    });

Example 4: javascript on click radio button get value

if (document.getElementById('r1').checked) {
  rate_value = document.getElementById('r1').value;
}

Tags:

Html Example