user1082764
user1082764

Reputation: 2015

How to change the text of a radio button

I have a radio button that needs to be dynamically updated from user input but the normal .val(), .text(), and .html() won't work. How can I change the text of a radio button using jQuery or plain JavaScript?

Upvotes: 3

Views: 20589

Answers (4)

Try this in JS.

<label id=labId for=labId     onClick="changeText(this.id)">RADIO BUTTON TEXT</label>
<input type=radio />

<script type="text/javascript">"use strict";
const stat=["Old Radio Button Label Text","NEW RADIO BUTTON LABEL TEXT"];
let   cptr=0;

function changeText(button_id){
   var el = document.getElementById(button_id);
   el.firstChild.data = stat[cptr^=1];
}
</script>

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

A radio button doesn't have text associated with it.

But if you have a label tag / span tag next to the radio option. then you can use .next to access that element and change its text/html

DEMO

HTML:

<input type="radio" /><label>Option 1</label>

or

<input type="radio" /><span>Option 1</span>

JS:

var $label = $('input[type=radio]').next();
$label.text('Options'); 

Or you can use the below hack to change the text next to radio option. Note that the below code assumes that text is next to radio option.

DEMO

var isRadioLabel = 0;
$('div').contents().each(function() {
    if (this.nodeName == '#text' && isRadioLabel == 1) {
        isRadioLabel = 2;
    }
    if (isRadioLabel == 2) {
        this.nodeValue = 'Options';
        isRadioLabel = 0;
    }
    if (this.type == 'radio') {
        isRadioLabel = 1;
    } else {
        isRadioLabel = 0;
    }
});

Upvotes: 1

Jeremy Banks
Jeremy Banks

Reputation: 129715

If your <label> has been properly associated with a particular radio button using the for attribute (as it should be)...

<form>
    <input type="radio" id="example" />
    <label for="example">Clickyclick</label>
</form>

...you can just search the DOM for it using by the for attribute. Using jQuery:

<script>
    var yourElement = $("#example");
    var itsLabel = $("[for=" + yourElement.attr("id") + "]"); // <---
    itsLabel.css("color", "red");
</script>

Try it in this fiddle.

Upvotes: 3

Naftali
Naftali

Reputation: 146302

A radio input does not have text

All it is is this:

<input type="radio" />

on and off radio inputs

Upvotes: 5

Related Questions