How to get value of selected radio button?

前端 未结 28 2737
温柔的废话
温柔的废话 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.

提交回复
热议问题