How do I get the label of the selected radio button using javascript

后端 未结 2 1966
囚心锁ツ
囚心锁ツ 2020-12-21 07:31

I have the following HTML

相关标签:
2条回答
  • 2020-12-21 07:56

    A radiobutton have no innerhtml. You need to target the label. If it's always directly after the radio-button, try something like radios[i].nextSibling.innerhtml.

    0 讨论(0)
  • 2020-12-21 07:58

    You have to access the corresponding label separately, since it resides in a separate tag. Because the labels' for attribute is equal to its option's id, you can get to the label easily:

    for(var i=0; i<radios.length; i++) {
        var selector = 'label[for=' + radios[i].id + ']';
        var label = document.querySelector(selector);
        var text = label.innerHTML;
        // do stuff
    }
    

    Also check out this fiddle

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