我如何知道通过 jQuery 选择了哪个单选按钮?

发布于 2024-07-14 11:15:05 字数 134 浏览 6 评论 0原文

我有两个单选按钮,想要发布所选按钮的值。 如何使用 jQuery 获取值?

我可以这样获取所有这些:

$("form :radio")

我如何知道选择了哪一个?

I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?

I can get all of them like this:

$("form :radio")

How do I know which one is selected?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

北城孤痞 2024-07-21 11:15:05

要获取 id 为 myForm 的表单的 selected radioName 项的值:

$('input[name=radioName]:checked', '#myForm').val()

以下是一个示例:

$('#myForm input').on('change', function() {
  alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
  <fieldset>
    <legend>Choose radioName</legend>
    <label><input type="radio" name="radioName" value="1" /> 1</label> <br />
    <label><input type="radio" name="radioName" value="2" /> 2</label> <br />
    <label><input type="radio" name="radioName" value="3" /> 3</label> <br />
  </fieldset>
</form>

To get the value of the selected radioName item of a form with id myForm:

$('input[name=radioName]:checked', '#myForm').val()

Here's an example:

$('#myForm input').on('change', function() {
  alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
  <fieldset>
    <legend>Choose radioName</legend>
    <label><input type="radio" name="radioName" value="1" /> 1</label> <br />
    <label><input type="radio" name="radioName" value="2" /> 2</label> <br />
    <label><input type="radio" name="radioName" value="3" /> 3</label> <br />
  </fieldset>
</form>

又怨 2024-07-21 11:15:05

用这个..

$("#myform input[type='radio']:checked").val();

Use this..

$("#myform input[type='radio']:checked").val();
酸甜透明夹心 2024-07-21 11:15:05

如果您已经引用了单选按钮组,例如:

var myRadio = $("input[name=myRadio]");

使用 filter() 函数,而不是 find()。 (find() 用于定位子/后代元素,而 filter() 用于搜索选择中的顶级元素。)

var checkedValue = myRadio.filter(":checked").val();

注释:答案最初是纠正另一个建议使用 find() 的答案,该答案似乎已被更改。 find() 对于已经引用了容器元素但没有引用单选按钮的情况仍然有用,例如:

var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();

If you already have a reference to a radio button group, for example:

var myRadio = $("input[name=myRadio]");

Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)

var checkedValue = myRadio.filter(":checked").val();

Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:

var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
云之铃。 2024-07-21 11:15:05

这应该有效:

$("input[name='radioName']:checked").val()

注意 input:checked 周围使用的“”,而不是像 Peter J 的解决方案那样的“”

This should work:

$("input[name='radioName']:checked").val()

Note the "" usaged around the input:checked and not '' like the Peter J's solution

铃予 2024-07-21 11:15:05

您可以将 :checked 选择器与单选选择器一起使用。

 $("form:radio:checked").val();

You can use the :checked selector along with the radio selector.

 $("form:radio:checked").val();
ペ泪落弦音 2024-07-21 11:15:05

如果您只想要布尔值,即是否选中它,请尝试以下操作:

$("#Myradio").is(":checked")

If you want just the boolean value, i.e. if it's checked or not try this:

$("#Myradio").is(":checked")
々眼睛长脚气 2024-07-21 11:15:05

获取所有无线电:

var radios = jQuery("input[type='radio']");

过滤以获取选中的无线电

radios.filter(":checked")

Get all radios:

var radios = jQuery("input[type='radio']");

Filter to get the one thats checked

radios.filter(":checked")
孤单情人 2024-07-21 11:15:05

另一种选择是:

$('input[name=radioName]:checked').val()

Another option is:

$('input[name=radioName]:checked').val()
独行侠 2024-07-21 11:15:05
$("input:radio:checked").val();
$("input:radio:checked").val();
合久必婚 2024-07-21 11:15:05

就我而言,我在一种表单中有两个单选按钮,我想知道每个按钮的状态。
下面这对我有用:

// get radio buttons value
console.log( "radio1: " +  $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " +  $('input[id=radio2]:checked', '#toggle-form').val() );


    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
  <div id="radio">
    <input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
    <input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
  </div>
</form>

In my case I have two radio buttons in one form and I wanted to know the status of each button.
This below worked for me:

// get radio buttons value
console.log( "radio1: " +  $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " +  $('input[id=radio2]:checked', '#toggle-form').val() );


    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
  <div id="radio">
    <input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
    <input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
  </div>
</form>

冷情妓 2024-07-21 11:15:05

以下是我编写表格并处理获取已检查收音机的方法。

使用名为 myForm 的表单:

<form id='myForm'>
    <input type='radio' name='radio1' class='radio1' value='val1' />
    <input type='radio' name='radio1' class='radio1' value='val2' />
    ...
</form>

从表单中获取值:

$('#myForm .radio1:checked').val();

如果您不发布表单,我将通过使用进一步简化它:

<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />

然后获取选中的值变为:

    $('.radio1:checked').val();

在输入上有一个类名可以让我轻松地设置样式输入...

Here's how I would write the form and handle the getting of the checked radio.

Using a form called myForm:

<form id='myForm'>
    <input type='radio' name='radio1' class='radio1' value='val1' />
    <input type='radio' name='radio1' class='radio1' value='val2' />
    ...
</form>

Get the value from the form:

$('#myForm .radio1:checked').val();

If you're not posting the form, I would simplify it further by using:

<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />

Then getting the checked value becomes:

    $('.radio1:checked').val();

Having a class name on the input allows me to easily style the inputs...

羁客 2024-07-21 11:15:05

试试这个。
这对我有用

$('input[type="radio"][name="name"]:checked').val();

try this one.
it worked for me

$('input[type="radio"][name="name"]:checked').val();
打小就很酷 2024-07-21 11:15:05

JSF 生成的单选按钮(使用 标记)中,您可以执行以下操作:

radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();

其中 selectOneRadio ID 为 radiobutton_id 并形成ID 为 form_id

请务必使用 name 而不是 id,如图所示,因为 jQuery 使用此属性(name 由 JSF 自动生成,类似于控件 ID)。

In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:

radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();

where selectOneRadio ID is radiobutton_id and form ID is form_id.

Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).

很酷不放纵 2024-07-21 11:15:05

另外,检查用户是否没有选择任何内容。

var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {           
   radioanswer = $('input[name=myRadio]:checked').val();
}

Also, check if the user does not select anything.

var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {           
   radioanswer = $('input[name=myRadio]:checked').val();
}
╭ゆ眷念 2024-07-21 11:15:05

如果您有单一形式的多个单选按钮,那么

var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();

var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();

这对我有用。

If you have Multiple radio buttons in single form then

var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();

var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();

This is working for me.

送舟行 2024-07-21 11:15:05

我编写了一个 jQuery 插件来设置和获取单选按钮值。 它还尊重他们身上的“改变”事件。

(function ($) {

    function changeRadioButton(element, value) {
        var name = $(element).attr("name");
        $("[type=radio][name=" + name + "]:checked").removeAttr("checked");
        $("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
        $("[type=radio][name=" + name + "]:checked").change();
    }

    function getRadioButton(element) {
        var name = $(element).attr("name");
        return $("[type=radio][name=" + name + "]:checked").attr("value");
    }

    var originalVal = $.fn.val;
    $.fn.val = function(value) {

        //is it a radio button? treat it differently.
        if($(this).is("[type=radio]")) {

            if (typeof value != 'undefined') {

                //setter
                changeRadioButton(this, value);
                return $(this);

            } else {

                //getter
                return getRadioButton(this);

            }

        } else {

            //it wasn't a radio button - let's call the default val function.
            if (typeof value != 'undefined') {
                return originalVal.call(this, value);
            } else {
                return originalVal.call(this);
            }

        }
    };
})(jQuery);

将代码放在任何地方以启用插件。 然后享受吧! 它只是覆盖默认的 val 函数而不会破坏任何东西。

您可以访问这个 jsFiddle 来尝试它,看看它是如何工作的。

小提琴

I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.

(function ($) {

    function changeRadioButton(element, value) {
        var name = $(element).attr("name");
        $("[type=radio][name=" + name + "]:checked").removeAttr("checked");
        $("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
        $("[type=radio][name=" + name + "]:checked").change();
    }

    function getRadioButton(element) {
        var name = $(element).attr("name");
        return $("[type=radio][name=" + name + "]:checked").attr("value");
    }

    var originalVal = $.fn.val;
    $.fn.val = function(value) {

        //is it a radio button? treat it differently.
        if($(this).is("[type=radio]")) {

            if (typeof value != 'undefined') {

                //setter
                changeRadioButton(this, value);
                return $(this);

            } else {

                //getter
                return getRadioButton(this);

            }

        } else {

            //it wasn't a radio button - let's call the default val function.
            if (typeof value != 'undefined') {
                return originalVal.call(this, value);
            } else {
                return originalVal.call(this);
            }

        }
    };
})(jQuery);

Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.

You can visit this jsFiddle to try it in action, and see how it works.

Fiddle

や莫失莫忘 2024-07-21 11:15:05
 $(".Stat").click(function () {
     var rdbVal1 = $("input[name$=S]:checked").val();
 }
 $(".Stat").click(function () {
     var rdbVal1 = $("input[name$=S]:checked").val();
 }
淡忘如思 2024-07-21 11:15:05

这工作正常

$('input[type="radio"][class="className"]:checked').val()

工作演示

:checked选择器适用于复选框单选按钮和选择元素。 仅对于选择元素,请使用 :selected 选择器。

:checked 选择器的 API

This works fine

$('input[type="radio"][class="className"]:checked').val()

Working Demo

The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.

API for :checked Selector

暗喜 2024-07-21 11:15:05

要获取使用类的选定无线电的值:

$('.class:checked').val()

To get the value of the selected radio that uses a class:

$('.class:checked').val()
冷默言语 2024-07-21 11:15:05

我使用这个简单的脚本

$('input[name="myRadio"]').on('change', function() {
  var radioValue = $('input[name="myRadio"]:checked').val();        
  alert(radioValue); 
});

I use this simple script

$('input[name="myRadio"]').on('change', function() {
  var radioValue = $('input[name="myRadio"]:checked').val();        
  alert(radioValue); 
});
陌上青苔 2024-07-21 11:15:05

用这个:

value = $('input[name=button-name]:checked').val();

Use this:

value = $('input[name=button-name]:checked').val();
小伙你站住 2024-07-21 11:15:05

演示https://jsfiddle.net/ipsjolly/xygr065w/

	$(function(){
	    $("#submit").click(function(){      
	        alert($('input:radio:checked').val());
	    });
	 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
       <tr>
         <td>Sales Promotion</td>
         <td><input type="radio" name="q12_3" value="1">1</td>
         <td><input type="radio" name="q12_3" value="2">2</td>
         <td><input type="radio" name="q12_3" value="3">3</td>
         <td><input type="radio" name="q12_3" value="4">4</td>
         <td><input type="radio" name="q12_3" value="5">5</td>
      </tr>
    </table>
<button id="submit">submit</button>

DEMO : https://jsfiddle.net/ipsjolly/xygr065w/

	$(function(){
	    $("#submit").click(function(){      
	        alert($('input:radio:checked').val());
	    });
	 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
       <tr>
         <td>Sales Promotion</td>
         <td><input type="radio" name="q12_3" value="1">1</td>
         <td><input type="radio" name="q12_3" value="2">2</td>
         <td><input type="radio" name="q12_3" value="3">3</td>
         <td><input type="radio" name="q12_3" value="4">4</td>
         <td><input type="radio" name="q12_3" value="5">5</td>
      </tr>
    </table>
<button id="submit">submit</button>

微暖i 2024-07-21 11:15:05

如果 1 个表单上只有 1 组单选按钮,则 jQuery 代码如下所示:

$( "input:checked" ).val()

If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:

$( "input:checked" ).val()
迷爱 2024-07-21 11:15:05

使用 $('input[name="radioName"]').filter(":checked").val(); 对我来说是最好的方法。

测试过,这可以工作

表单

<form id="myForm">
  <input type="radio" name="radioName" value="Option1"> Option1
  <input type="radio" name="radioName" value="Option2" checked> Option2
  <input type="radio" name="radioName" value="Option3"> Option3
</form>

Jquery

$(document).ready(function() {
  $('input[name="radioName"]').on('change', function() {
     const val = $(this).filter(":checked").val();
     alert(val);
  })

  // First load check
  const val = $('input[name="radioName"]').filter(":checked").val();
  alert(val);
});

示例如下:
https://codepen.io/abinhho/pen/mdLrqbX

Using $('input[name="radioName"]').filter(":checked").val(); is the best way for me.

Tested, this works

Form

<form id="myForm">
  <input type="radio" name="radioName" value="Option1"> Option1
  <input type="radio" name="radioName" value="Option2" checked> Option2
  <input type="radio" name="radioName" value="Option3"> Option3
</form>

Jquery

$(document).ready(function() {
  $('input[name="radioName"]').on('change', function() {
     const val = $(this).filter(":checked").val();
     alert(val);
  })

  // First load check
  const val = $('input[name="radioName"]').filter(":checked").val();
  alert(val);
});

Example here:
https://codepen.io/abinhho/pen/mdLrqbX

岛徒 2024-07-21 11:15:05

我已经发布了一个库来帮助解决这个问题。 实际上,提取所有可能的输入值,但还包括选中了哪个单选按钮。 您可以在 https://github.com/mazondo/formalizedata 查看它,

它会给您一个js 对象的答案,所以像这样的形式:

<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>

会给你:

$("form").formalizeData()
{
  "favorite-color" : "blue"
}

I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata

It'll give you a js object of the answers, so a form like:

<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>

will give you:

$("form").formalizeData()
{
  "favorite-color" : "blue"
}
旧伤慢歌 2024-07-21 11:15:05

JQuery 获取表单中的所有单选按钮和选中的值。

$.each($("input[type='radio']").filter(":checked"), function () {
  console.log("Name:" + this.name);
  console.log("Value:" + $(this).val());
});

JQuery to get all the radio buttons in the form and the checked value.

$.each($("input[type='radio']").filter(":checked"), function () {
  console.log("Name:" + this.name);
  console.log("Value:" + $(this).val());
});
甜宝宝 2024-07-21 11:15:05

要检索 JavaScript 数组中的所有单选按钮值,请使用以下 jQuery 代码:

var values = jQuery('input:checkbox:checked.group1').map(function () {
    return this.value;
}).get();

To retrieve all radio buttons values in JavaScript array use following jQuery code :

var values = jQuery('input:checkbox:checked.group1').map(function () {
    return this.value;
}).get();
飘逸的'云 2024-07-21 11:15:05

尝试一下-

var radioVal = $("#myform").find("input[type='radio']:checked").val();

console.log(radioVal);

try it-

var radioVal = $("#myform").find("input[type='radio']:checked").val();

console.log(radioVal);
中二柚 2024-07-21 11:15:05

另一种获取方式:

 $("#myForm input[type=radio]").on("change",function(){
   if(this.checked) {
    alert(this.value);
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
   <span><input type="radio" name="q12_3" value="1">1</span><br>
   <span><input type="radio" name="q12_3" value="2">2</span>
</form>

Another way to get it:

 $("#myForm input[type=radio]").on("change",function(){
   if(this.checked) {
    alert(this.value);
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
   <span><input type="radio" name="q12_3" value="1">1</span><br>
   <span><input type="radio" name="q12_3" value="2">2</span>
</form>

温馨耳语 2024-07-21 11:15:05

这个问题中,我想出了另一种方法来访问当前选定的输入,当您位于其各自标签的 click 事件中。 原因是新选择的 input 直到其 label 的点击事件之后才会更新。

TL;DR

$('label').click(function() {
  var selected = $('#' + $(this).attr('for')).val();

  ...
});

$(function() {
  // this outright does not work properly as explained above
  $('#reported label').click(function() {
    var query = $('input[name="filter"]:checked').val();
    var time = (new Date()).toString();

    $('.query[data-method="click event"]').html(query + ' at ' + time);
  });

  // this works, but fails to update when same label is clicked consecutively
  $('#reported input[name="filter"]').on('change', function() {
    var query = $('input[name="filter"]:checked').val();
    var time = (new Date()).toString();

    $('.query[data-method="change event"]').html(query + ' at ' + time);
  });

  // here is the solution I came up with
  $('#reported label').click(function() {
    var query = $('#' + $(this).attr('for')).val();
    var time = (new Date()).toString();

    $('.query[data-method="click event with this"]').html(query + ' at ' + time);
  });
});
input[name="filter"] {
  display: none;
}
#reported label {
  background-color: #ccc;
  padding: 5px;
  margin: 5px;
  border-radius: 5px;
  cursor: pointer;
}
.query {
  padding: 5px;
  margin: 5px;
}
.query:before {
  content: "on " attr(data-method)": ";
}
[data-method="click event"] {
  color: red;
}
[data-method="change event"] {
  color: #cc0;
}
[data-method="click event with this"] {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
  <input type="radio" name="filter" id="question" value="questions" checked="checked">
  <label for="question">Questions</label>

  <input type="radio" name="filter" id="answer" value="answers">
  <label for="answer">Answers</label>

  <input type="radio" name="filter" id="comment" value="comments">
  <label for="comment">Comments</label>

  <input type="radio" name="filter" id="user" value="users">
  <label for="user">Users</label>

  <input type="radio" name="filter" id="company" value="companies">
  <label for="company">Companies</label>

  <div class="query" data-method="click event"></div>
  <div class="query" data-method="change event"></div>
  <div class="query" data-method="click event with this"></div>
</form>

From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.

TL;DR

$('label').click(function() {
  var selected = $('#' + $(this).attr('for')).val();

  ...
});

$(function() {
  // this outright does not work properly as explained above
  $('#reported label').click(function() {
    var query = $('input[name="filter"]:checked').val();
    var time = (new Date()).toString();

    $('.query[data-method="click event"]').html(query + ' at ' + time);
  });

  // this works, but fails to update when same label is clicked consecutively
  $('#reported input[name="filter"]').on('change', function() {
    var query = $('input[name="filter"]:checked').val();
    var time = (new Date()).toString();

    $('.query[data-method="change event"]').html(query + ' at ' + time);
  });

  // here is the solution I came up with
  $('#reported label').click(function() {
    var query = $('#' + $(this).attr('for')).val();
    var time = (new Date()).toString();

    $('.query[data-method="click event with this"]').html(query + ' at ' + time);
  });
});
input[name="filter"] {
  display: none;
}
#reported label {
  background-color: #ccc;
  padding: 5px;
  margin: 5px;
  border-radius: 5px;
  cursor: pointer;
}
.query {
  padding: 5px;
  margin: 5px;
}
.query:before {
  content: "on " attr(data-method)": ";
}
[data-method="click event"] {
  color: red;
}
[data-method="change event"] {
  color: #cc0;
}
[data-method="click event with this"] {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
  <input type="radio" name="filter" id="question" value="questions" checked="checked">
  <label for="question">Questions</label>

  <input type="radio" name="filter" id="answer" value="answers">
  <label for="answer">Answers</label>

  <input type="radio" name="filter" id="comment" value="comments">
  <label for="comment">Comments</label>

  <input type="radio" name="filter" id="user" value="users">
  <label for="user">Users</label>

  <input type="radio" name="filter" id="company" value="companies">
  <label for="company">Companies</label>

  <div class="query" data-method="click event"></div>
  <div class="query" data-method="change event"></div>
  <div class="query" data-method="click event with this"></div>
</form>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文