Search code examples
javascripthtmlfunctionradio-button

Whenever I click on the radio button I get the error of function is not defined at HTMLInputElement.onclick


I'm having a problem calling the function when the radio button is clicked; in particular I get

showinputfield is not defined at HTMLInputElement.onclick

This is my code:

function showinputfield() {
    let radio1 = document.getElementById('flexRadio1');
    let radio2 = document.getElementById('flexRadio2');
    if(radio1.checked) {
        console.log('hello1');
    } else if(radio2.checked) {
        console.log('hello2');
    }
}
<div class="form-check mb-3">
   <input class="form-check-input" type="radio" name="flexRadio1" id="flexRadio1" value="radio1" onclick="showinputfield()">
     <label class="form-check-label" for="flexRadio1"> Radio1 </label>
</div>
<div class="form-check mb-3">
   <input class="form-check-input" type="radio" name="flexRadio2" id="flexRadio2" value="radio2" onclick="showinputfield()">
      <label class="form-check-label" for="flexRadio2"> Radio2 </label>
</div>

Can you help me please?


Solution

  • If it's defined in the same html file, this javascript code should go between

    <script>
       function showinputfield() {
        ...
       }
    </script>
    

    If it's defined in another file, please check if it's included as <script type="text/javascript" src="yourScript.js">.