How to change the switch text

I have a switch that must be dynamically updated with the user input, but normal .val()

, .text()

and .html()

will not work. How do I change the text of a radio button using jQuery or plain JavaScript?

+3


source to share


3 answers


The toggle has no text associated with it.

But if you have a parameter label tag / span tag

next to the radio. then you can use .next

to access this element and change ittext/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 bottom hack to change the text next to the radio option. Note that the code below assumes the text is next to the radio parameter.

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;
    }
});

      

+1


source


Radio input has no text

It's all like this:



<input type="radio" />

      

on and off radio inputs

+5


source


If yours <label>

was correctly associated with a specific radio button using the attribute for

(as it should) ...

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

      

... you can just search the DOM for it using the attribute for

. Using jQuery:

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

      

Try this script .

+2


source







All Articles