Skip to content Skip to sidebar Skip to footer

Javascript - How To Dynamically Change Information Displayed By Radio Button?

(Duplicate?) I've tried several Stackoverflow postings related to this, but I cannot get a javaScript example to work. I'd like to avoid having to use jQuery, for the time being. I

Solution 1:

I Have made some modifications for getting label through document.getElementByTagName() and also some changes to OnSubmitForm() function. And just pasted your code with those changes below and demo link at the end.

 <html>
<form name="myform" onsubmit="OnSubmitForm();">
   <input type="radio" id = 'first'  name="operation" value="1"
          checked> <label for="alsoFirst"> Answer 1 </label>
   <input type="radio" id = 'second'  name="operation" value="2">
  <label for="alsoSecond">Answer 2</label>

   <p>
   <input type="submit" name="submit" value="save">
   </p>
</form>



<script type="text/javascript">
 document.addEventListener('readystatechange', function() {
  // Seems like a GOOD PRACTICE - keeps me from getting type error I was getting

    // http://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object

    if (document.readyState === "complete") {
      init();
    }
  });

 function init() {

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


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

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

  return false;
}

/*
<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';

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




</html>

Demo : https://jsbin.com/sojojiy/27/edit?html,console,output

Hope this helps. Thanks !


Post a Comment for "Javascript - How To Dynamically Change Information Displayed By Radio Button?"