Suvansh Chawla Suvansh Chawla - 11 days ago 7
HTML Question

linking select with radio using jquery

I am fairly new at jQuery, so I was trying to change the value of a radio box, automatically as I select an option from the from my select dropdown. But it is not going as I planned.

For eg:
If I select Mrs. or Ms. from the select options then the property of the radio with value female should become true.



<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$('[name="title"]').change(function() {
if ($(this).val() == "Ms." || $(this).val() == "Mrs.") {
$("#female").prop("checked", true);
} else if ($(this).val() == "Mr.") {
$("#male").prop("checked", true);
}
});
</script>
</head>

<body>
<select name="title">
<option value="" disabled selected>Choose your option</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Ms.">Ms.</option>
</select>
<label>Title</label>

<p><b>Gender</b>
<br/>
</p>
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
</body>

<html>




Answer

Your code appears to be correct. Try just using a document.ready, or loading it at the end of the body.

<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
        $('[name="title"]').change(function() {
          if ($(this).val() == "Ms." || $(this).val() == "Mrs.") {
            $("#female").prop("checked", true);
          } else if ($(this).val() == "Mr.") {
            $("#male").prop("checked", true);
          }
        });
    });
  </script>
</head>

<body>
  <select name="title">
    <option value="" disabled selected>Choose your option</option>
    <option value="Mr.">Mr.</option>
    <option value="Mrs.">Mrs.</option>
    <option value="Ms.">Ms.</option>
  </select>
  <label>Title</label>

  <p><b>Gender</b>
    <br/>
  </p>
  <input type="radio" name="gender" id="male">
  <label for="male">Male</label>
  <input type="radio" name="gender" id="female">
  <label for="female">Female</label>
</body>

<html>