How to get the selected radio button’s value?

后端 未结 18 1834
北海茫月
北海茫月 2020-11-22 00:57

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button

18条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 01:06

    This is pure JavaScript, based on the answer by @Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:

    var genderSRadio = document.querySelector("input[name=genderS]:checked");
    var genderSValue = genderSRadio ? genderSRadio.value : "";
    

    The code breaks down like this:

    • Line 1: get a reference to the control that (a) is an type, (b) has a name attribute of genderS, and (c) is checked.
    • Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.

    For JQuery, use @jbabey's answer, and note that if there isn't a selected radio button it will return undefined.

提交回复
热议问题