如何用jQuery知道哪个单选按钮被选中

如何用jQuery知道哪个单选按钮被选中

为了检查表单中哪个单选按钮被选中,我们首先得到所需的输入组,输入的类型为选项,然后可以通过val()方法访问这个选项的值。这将返回当前被选中的选项的名称。

选择器'input[name=option]:checked'用于选择指定表单中所有具有选项类型的输入组。

语法:

$('input[name=option]:checked', 'formName').val()

这在下面的例子中显示。
示例:

<!DOCTYPE html>
<html>
<head>
    <title>
      How to know which radio button
      is selected via jQuery?
  </title>
</head>
  
<body>
    <h1 style="color: green">
      GeeksForGeeks
  </h1>
    <b>
      How to know which radio 
      button is selected via jQuery?
  </b>
    <p>
        <form id="myForm">
            <label>
                <input 
                       type="radio"
                       name="option" 
                       value="free">
              Free Membership
            </label>
            <label>
                <input type="radio" 
                       name="option" 
                       value="premium">
              Premium Membership
            </label>
        </form>
    
    
    <p>
      The value of the option selected is: 
      <span class="output"></span>
  </p>
    <button id="btn">
      Check option button
  </button>
    
    <script src=
"https://code.jquery.com/jquery-2.2.4.min.js">
  </script>
    
    <script type="text/javascript">
        
      // Check the radio button value.
        ('#btn').on('click', function() {
            output = 
              ('input[name=option]:checked',
                '#myForm').val();
            
            document.querySelector(
              '.output').textContent = output;
        });
    </script>
</body>
  
</html>

输出:

点击第一个选项后检查:
如何用jQuery知道哪个单选按钮被选中?

点击第二个选项后检查:
如何用jQuery知道哪个单选按钮被选中?

jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程