How to get value of selected radio button?

前端 未结 28 2241
温柔的废话
温柔的废话 2020-11-22 03:51

I want to get the selected value from a group of radio buttons.

Here\'s my HTML:

相关标签:
28条回答
  • 2020-11-22 04:54

    Assuming your form element is referred to by myForm variable below, and that your radio buttons share the name "my-radio-button-group-name", the following is pure JavaScript and standards compliant (although I have not checked it to be available everywhere):

    myForm.elements.namedItem("my-radio-button-group-name").value
    

    The above will yield the value of a checked (or selected, as it is also called) radio button element, if any, or null otherwise. The crux of the solution is the namedItem function which works with radio buttons specifically.

    See HTMLFormElement.elements, HTMLFormControlsCollection.namedItem and especially RadioNodeList.value, as namedItem usually returns a RadioNodeList object.

    I use MDN because it allows one to track standards compliance, at least to a large degree, and because it is easier to comprehend than many WhatWG and W3C publications.

    0 讨论(0)
  • 2020-11-22 04:56

    https://codepen.io/anon/pen/YQxbZJ

    The HTML

    <div id="rates">
    <input type="radio" id="x1" name="rate" value="Fixed Rate"> Fixed Rate
    <input type="radio" id="x2" name="rate" value="Variable Rate" 
    checked="checked"> Variable Rate
    <input type="radio" id="x3" name="rate" value="Multi Rate" > Multi Rate
    </div>
    
    <button id="rdio"> Check Radio </button>
    <div id="check">
    
    </div>
    

    The JS

    var x ,y;
    var x = document.getElementById("check");
    function boom()
    {
    if (document.getElementById("x1").checked)
      y = document.getElementById("x1").value;
    
    else if(document.getElementById("x2").checked)
      y = document.getElementById("x2").value;
    
    else if (document.getElementById("x3").checked)
      y = document.getElementById("x3").value;
    else
      y = "kuch nhi;"
    x.innerHTML = y;
    }
    
    var z = document.getElementById('rdio');
    z.addEventListener("click", boom);`
    
    0 讨论(0)
  • 2020-11-22 04:57
    var rates = document.getElementById('rates').value;
    

    The rates element is a div, so it won't have a value. This is probably where the undefined is coming from.

    The checked property will tell you whether the element is selected:

    if (document.getElementById('r1').checked) {
      rate_value = document.getElementById('r1').value;
    }
    
    0 讨论(0)
  • 2020-11-22 04:57

    In Javascript we can get the values by using Id's "getElementById()" in the above code you posted has contain name not Id so you to modify like this

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

    use this rate_value according to your code

    0 讨论(0)
提交回复
热议问题