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
Solution 1:
Solution 2:
If your <label>
has been properly associated with a particular radio button using the for
attribute (as it should be)...
<form><inputtype="radio"id="example" /><labelfor="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.
Solution 3:
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
HTML:
<inputtype="radio" /><label>Option 1</label>
or
<inputtype="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.
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;
}
});
Post a Comment for "How To Change The Text Of A Radio Button"