Mohsen Rahnamaei Mohsen Rahnamaei - 6 months ago 8
Javascript Question

Check of specific radio button is checked and it doesn't work

I want to show the ptext when radio button has checked and hide when another radio button is active
but does not work

This is my code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<input id="postageyes" name="type" value="Paint" type="radio">Paint
<br>
<input id="postageno" name="type" value="Sculpture" type="radio">Sculpture
<br>
<input id="postageno" name="type" value="calligraphy" type="radio">calligraphy
<br>
<input id="stext" name="type" value="type" type="text"><br>
<input id="ctext" name="type" value="type" type="text"><br>
<input id="ptext" name="type" value="type" type="text">
<script type="text/javascript">

$('input:radio[name="postage"]').change(function() {
if ($(this).val() == 'Paint') {
$("#ptext").show();
} else {
$("#ptext").hide();
}
});

</script>



</body>
</html>

Answer

You have two major issues:

  • The value of id should be unique.
  • There's no input with name as postage.
  • Extra: Better to hide the ptext when loading the page.

Change the name to postage:

<input id="postageyes" name="postage" value="Paint" type="radio">Paint
<br>
<input id="postageno1" name="postage" value="Sculpture" type="radio">Sculpture
<br>
<input id="postageno2" name="postage" value="calligraphy" type="radio">calligraphy

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="postageyes" name="postage" value="Paint" type="radio">Paint
<br>
<input id="postageno1" name="postage" value="Sculpture" type="radio">Sculpture
<br>
<input id="postageno2" name="postage" value="calligraphy" type="radio">calligraphy
<br>
<input id="stext" name="type" value="type" type="text"><br>
<input id="ctext" name="type" value="type" type="text"><br>
<input id="ptext" name="type" value="type" type="text">
<script type="text/javascript">
  $("#ptext").hide();
  $('input:radio[name="postage"]').change(function() {
    if ($(this).val() == 'Paint') {
      $("#ptext").show();
    } else {
      $("#ptext").hide();
    }
  });

</script>

Also, it is better to hide it when you load the document. See the above example.