How do I get the text of a radio button (not the value)

后端 未结 4 1986
夕颜
夕颜 2021-01-21 05:48

I know I can get the \"value\" attribute of a radiobutton but I\'m finding it strangely difficult to get the text of the radiobutton.

Consider the example below. It has

4条回答
  •  粉色の甜心
    2021-01-21 06:23

    I added this answer because previously there was no full solution to the question.
    Below code uses two prototype functions from the Array object:

    1. forEach to add click event listener for each radio node

    2. filter to retrieve checked radio node

    as the RadioNodeList does not have those functionalities build-in.

    var rblist = document.getElementsByName("colors");;
    
    [].forEach.call(rblist, function(e) {
      e.addEventListener('click', showText, false)
    });
    
    function showText() {
      var rb = [].filter.call(rblist, function(e) {
        return e.checked;
      })[0];
      console.log(rb.nextElementSibling.innerText);
    };
    
    
    

提交回复
热议问题