javascript - 使用 jquery 将 select 与 radio 链接起来

标签 javascript jquery html

我对 jQuery 相当陌生,所以当我从选择下拉列表中选择一个选项时,我试图自动更改单选框的值。但事情并没有按我的计划进行。

例如: 如果我从选择选项中选择“夫人”或“女士”,则具有“女性”值的 radio 的属性应该变为 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>

最佳答案

您的代码似乎是正确的。尝试仅使用 document.ready,或将其加载到正文末尾。

<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>

关于javascript - 使用 jquery 将 select 与 radio 链接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40811795/

相关文章:

javascript - 我如何使用 javascript 和 php 在 $_GET 获取数组?

javascript - 如何避免 "Internet Explorer restricted this webpage from running scripts or ActiveX Controls"消息?

javascript - 在没有表单或 URL 变量的情况下将所选 DIV 的 ID 传递到下一个 PHP 页面

javascript - 有人可以解释为什么这个测试显示 jquery $.each 比原生更快吗?

javascript - 当不再悬停时延迟隐藏 CSS 子菜单

javascript - 我可以使用html5音频api创建歌曲吗

javascript - .click 函数在 ajax POST 中不起作用

javascript - AJAX POST 请求上没有方法错误

javascript - 如何通过表单发送裁剪后的图像

javascript - 循环 JSON 数组并创建单个 JSON 字符串