<input> 和 <form> 标签

<form> 标记将 HTML 表单添加到网页以供用户输入。

表单将用户提交的数据传递给服务器。
<input> 元素在 <form> 标签中使用,指定用户输入的字段。

字段的类型由 type 属性的值决定。
输入类型之一是收音机,它创建一个单选按钮。
选择一个单选按钮时,将禁用所有其他单选按钮。
单选按钮显示在单选组中,单选按钮是描述相关选项集合的单选按钮集合。

如何使用 jQuery 检查单选按钮

在本教程中,我们将展示使用 jQuery 检查单选按钮的正确方法。

假设我们有以下代码:

<form>
  <div id='type'>
    <input type='radio' id='radio1' name='type' value='1' />
    <input type='radio' id='radio2' name='type' value='2' />
    <input type='radio' id='radio3' name='type' value='3' /> 
  </div>
</form>

现在,让我们来看看如何使用 jQuery 进行检查。

对于等于或者高于 1.6 的 jQuery 版本,我们可以使用:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  </head>
  <body>
    <input type='radio' id='radio1' name='type' value='1'>Value1 </input>
    <input type='radio' id='radio2' name='type' value='2'>Value2 </input>
    <input type='radio' id='radio3' name='type' value='3'> Value3 </input>
    <script>
      $(document).ready(function() {
          $("#radio1").prop("checked", true);
        });
    </script>
  </body>
</html>

对于 1.6 之前的版本,我们可以使用:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <script src="https://code.jquery.com/jquery-1.5.min.js"></script>
  </head>
  <body>
    <input type='radio' id='radio1' name='type' value='1'>Value1 </input>
    <input type='radio' id='radio2' name='type' value='2'>Value2 </input>
    <input type='radio' id='radio3' name='type' value='3'> Value3 </input>
    <script>
      $(document).ready(function() {
          $("#radio3").attr('checked', 'checked');
        });
    </script>
  </body>
</html>

我们还可以在末尾添加 .change() 以触发页面上的任何其他事件。

要更新组中的其他单选按钮,我们可以使用:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  </head>
  <body>
    <input type='radio' id='radio1' name='type' value='1'>Value1 </input>
    <input type='radio' id='radio2' name='type' value='2'>Value2 </input>
    <input type='radio' id='radio3' name='type' value='3'> Value3 </input>
    <script>
      $(document).ready(function() {
          $("#radio2").prop("checked", true).trigger("click");
        });
    </script>
  </body>
</html>
日期:2020-06-02 22:16:09 来源:oir作者:oir