Skip to content Skip to sidebar Skip to footer

Javascript How To Change Radio Button Label Text?

I want to change the text of the label which is associated with the radiobutton id='male'. I have tried various ways to do it, but i can't make it work. I want to change the text '

Solution 1:

You can use

var r = document.getElementsByTagName("label")   

to select all the label element in your page and then use

r[0].innerHTML ="new text"

to select first label and set the text to "next text" in your test() function

Solution 2:

I tried to use ideas from the above to get a working example, and had some problems. So I asked for help in another posting and @KrishCdbry very kindly fixed the problem. The posted question is at javascript - How to dynamically change information displayed by radio button? Below is the working example with Krish's changes

<html><formname="myform"onsubmit="OnSubmitForm();"><inputtype="radio"id = 'first'name="operation"value="1"checked><labelfor="alsoFirst"> Answer 1 </label><inputtype="radio"id = 'second'name="operation"value="2"><labelfor="alsoSecond">Answer 2</label><p><inputtype="submit"name="submit"value="save"></p></form><scripttype="text/javascript">document.addEventListener('readystatechange', function() {
  // Seems like a GOOD PRACTICE - keeps me from getting type error I was getting// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-objectif (document.readyState === "complete") {
      init();
    }
  });

 functioninit() {

    console.log ("expect to change -Answer 1- displayed by first button to word junk");


     // this worksvar label = document.getElementsByTagName('label') [0];
    // this does not work
    label.innerHTML = 'junk';
    }

//http://www.javascript-coder.com/html-form/html-form-action.phtmlfunctionOnSubmitForm()
{
  if(document.getElementById('first').checked == true)
    {
    alert ( "You have selected the first answer" );  
    }
  elseif(document.getElementById('second').checked == true)
        {
        alert ( "You have selected the SECOND answer" );  
        }

  returnfalse;
}

/*
<input type="radio" name="sex" id="male" value="male">
        <label for="male">Male</label>
  </input>

var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';

*///https://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text</script></html>

Solution 3:

With jQuery, $('label[for=male]').html('New Label');

Plain JS:

var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';

Can also chain that together:

var label = document.getElementById('male').getElementsByTagName('label')[0];
label.innerHTML = 'New Text;

Post a Comment for "Javascript How To Change Radio Button Label Text?"