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

时间:2022-04-20 06:59:04

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

我有两个单选按钮,希望发布所选按钮的值。如何使用jQuery获得值?

I can get all of them like this:

我可以像这样得到它们:

$("form :radio")

How do I know which one is selected?

我如何知道哪一个被选中?

29 个解决方案

#1


3494  

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

以id myForm获取表单中选定的radioName项的值:

$('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">
  <input type="radio" name="radioName" value="1" /> 1 <br />
  <input type="radio" name="radioName" value="2" /> 2 <br />
  <input type="radio" name="radioName" value="3" /> 3 <br />
</form>

#2


366  

Use this..

使用这个. .

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

#3


252  

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

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

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

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

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

#4


118  

This should work:

这应该工作:

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

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

注意“在输入周围使用:检查而不是”,就像Peter J的解决方案一样

#5


69  

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

您可以使用:选中的选择器和无线电选择器。

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

#6


42  

Get all radios:

得到所有收音机:

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

Filter to get the one thats checked

过滤器,以得到检查。

radios.filter(":checked")

#7


41  

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

如果你只想要布尔值,也就是说,如果它被选中或不被选中,试试这个:

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

#8


35  

Another option is:

另一个选项是:

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

#9


25  

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

#10


19  

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

这是我如何写表格和处理收到检查过的收音机。

Using a form called myForm:

使用一种叫做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...

在输入中有一个类名,可以方便地对输入进行样式化……

#11


17  

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>

#12


14  

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

在JSF生成的单选按钮中(使用 标记),您可以这样做:

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

where selectOneRadio ID is radiobutton_id and form ID is form_id.

其中selectOneRadio ID为radiobutton_id, form ID为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).

请务必使用name而不是id,如所示,因为jQuery使用这个属性(名称是由类似于control id的JSF自动生成的)。

#13


14  

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();
}

#14


14  

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.

这对我很有效。

#15


14  

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

我编写了一个jQuery插件来设置和获取radio-button值。它也尊重他们的“改变”事件。

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

将代码放在任何地方以启用插件。然后享受!它只是在不破坏任何东西的情况下重写默认的val函数。

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

您可以访问这个jsFiddle,以实际操作它,并查看它是如何工作的。

Fiddle

小提琴

#16


11  

 $(".Stat").click(function () {
     var rdbVal1 = $("input[name$=S]:checked").val();
 }

#17


11  

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

要获取使用类的所选收音机的值:

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

#18


11  

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.

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

API for :checked Selector

API:检查选择器

#19


9  

I use this simple script

我使用这个简单的脚本

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

#20


9  

Use this:

用这个:

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

#21


6  

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

如果一个表单上只有一组单选按钮,jQuery代码就是这么简单:

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

#22


5  

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

演示: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>

#23


4  

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

我已经发布了一个图书馆来帮助这一点。实际上,拉出所有可能的输入值,但也包括检查了哪个单选按钮。您可以在https://github.com/mazondo/formalizedata上查看

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

它会给你一个js对象的答案,这样的形式是:

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

#24


4  

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

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

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

#25


3  

try it-

试一试,

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

console.log(radioVal);

#26


1  

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

博士TL;

$('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>

#27


1  

$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
    var radValue= "";
    $(this).find('input[type=radio]:checked').each(function () {
        radValue= $(this).val();
    });
  })
});

#28


1  

What I needed to do was simplify C# code, that is do as much as possible in the front end JavaScript. I'm using a fieldset container because I'm working in DNN and it has its own form. So I can't add a form.

我需要做的是简化c#代码,即尽可能多地在前端JavaScript中执行。我使用一个fieldset容器,因为我在DNN中工作,它有自己的形式。所以我不能添加一个表单。

I need to test which text box out of 3 is being used and if it is, what's the type of search? Starts with the value, Contains the value, Exact Match of the value.

我需要测试的是,3中哪个文本框被使用了,如果是,搜索的类型是什么?从值开始,包含值,值的精确匹配。

HTML:

HTML:

<fieldset id="fsPartNum" class="form-inline">
<div class="form-group">
    <label for="txtPartNumber">Part Number:</label>
    <input type="text" id="txtPartNumber" class="input-margin-pn" />
</div>
<div class="form-group">
    <label for="radPNStartsWith">Starts With: </label>
    <input type="radio" id="radPNStartsWith" name="partNumber" checked  value="StartsWith"/>
</div>
<div class="form-group">
    <label for="radPNContains">Contains: </label>
    <input type="radio" id="radPNContains" name="partNumber" value="Contains" />
</div>
<div class="form-group">
    <label for="radPNExactMatch">Exact Match: </label>
    <input type="radio" id="radPNExactMatch" name="partNumber" value="ExactMatch" />
</div>

And my JavaScript is:

我的观点是:JavaScript

        alert($('input[name=partNumber]:checked', '#fsPartNum').val()); 
    if(txtPartNumber.val() !== ''){
        message = 'Customer Part Number';
    }
    else if(txtCommercialPartNumber.val() !== ''){

    }
    else if(txtDescription.val() !== ''){

    }

Just saying any containing tag with an ID can be used. For DNNers, this is good to know. The end goal here is pass to the mid-level code what is needed to start a parts search in SQL Server.

就是说任何包含ID的标签都可以使用。对于DNNers,这是很好的了解。这里的最终目标是将在SQL Server中启动部分搜索所需的内容传递给中级代码。

This way I don't have to copy the much more complicated previous C# code also. The heavy lifting is being done right here.

这样,我就不必复制更复杂的c#代码了。这里正在进行繁重的工作。

I had to look a bit for this and then tinker with it to get it to work. So for other DNNers, hopefully this is easy to find.

我得找点东西,然后修改一下才能让它工作。所以对于其他dnner,希望这个很容易找到。

#29


1  

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>

#1


3494  

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

以id myForm获取表单中选定的radioName项的值:

$('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">
  <input type="radio" name="radioName" value="1" /> 1 <br />
  <input type="radio" name="radioName" value="2" /> 2 <br />
  <input type="radio" name="radioName" value="3" /> 3 <br />
</form>

#2


366  

Use this..

使用这个. .

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

#3


252  

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

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

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

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

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

#4


118  

This should work:

这应该工作:

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

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

注意“在输入周围使用:检查而不是”,就像Peter J的解决方案一样

#5


69  

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

您可以使用:选中的选择器和无线电选择器。

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

#6


42  

Get all radios:

得到所有收音机:

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

Filter to get the one thats checked

过滤器,以得到检查。

radios.filter(":checked")

#7


41  

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

如果你只想要布尔值,也就是说,如果它被选中或不被选中,试试这个:

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

#8


35  

Another option is:

另一个选项是:

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

#9


25  

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

#10


19  

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

这是我如何写表格和处理收到检查过的收音机。

Using a form called myForm:

使用一种叫做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...

在输入中有一个类名,可以方便地对输入进行样式化……

#11


17  

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>

#12


14  

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

在JSF生成的单选按钮中(使用 标记),您可以这样做:

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

where selectOneRadio ID is radiobutton_id and form ID is form_id.

其中selectOneRadio ID为radiobutton_id, form ID为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).

请务必使用name而不是id,如所示,因为jQuery使用这个属性(名称是由类似于control id的JSF自动生成的)。

#13


14  

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();
}

#14


14  

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.

这对我很有效。

#15


14  

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

我编写了一个jQuery插件来设置和获取radio-button值。它也尊重他们的“改变”事件。

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

将代码放在任何地方以启用插件。然后享受!它只是在不破坏任何东西的情况下重写默认的val函数。

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

您可以访问这个jsFiddle,以实际操作它,并查看它是如何工作的。

Fiddle

小提琴

#16


11  

 $(".Stat").click(function () {
     var rdbVal1 = $("input[name$=S]:checked").val();
 }

#17


11  

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

要获取使用类的所选收音机的值:

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

#18


11  

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.

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

API for :checked Selector

API:检查选择器

#19


9  

I use this simple script

我使用这个简单的脚本

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

#20


9  

Use this:

用这个:

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

#21


6  

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

如果一个表单上只有一组单选按钮,jQuery代码就是这么简单:

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

#22


5  

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

演示: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>

#23


4  

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

我已经发布了一个图书馆来帮助这一点。实际上,拉出所有可能的输入值,但也包括检查了哪个单选按钮。您可以在https://github.com/mazondo/formalizedata上查看

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

它会给你一个js对象的答案,这样的形式是:

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

#24


4  

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

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

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

#25


3  

try it-

试一试,

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

console.log(radioVal);

#26


1  

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

博士TL;

$('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>

#27


1  

$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
    var radValue= "";
    $(this).find('input[type=radio]:checked').each(function () {
        radValue= $(this).val();
    });
  })
});

#28


1  

What I needed to do was simplify C# code, that is do as much as possible in the front end JavaScript. I'm using a fieldset container because I'm working in DNN and it has its own form. So I can't add a form.

我需要做的是简化c#代码,即尽可能多地在前端JavaScript中执行。我使用一个fieldset容器,因为我在DNN中工作,它有自己的形式。所以我不能添加一个表单。

I need to test which text box out of 3 is being used and if it is, what's the type of search? Starts with the value, Contains the value, Exact Match of the value.

我需要测试的是,3中哪个文本框被使用了,如果是,搜索的类型是什么?从值开始,包含值,值的精确匹配。

HTML:

HTML:

<fieldset id="fsPartNum" class="form-inline">
<div class="form-group">
    <label for="txtPartNumber">Part Number:</label>
    <input type="text" id="txtPartNumber" class="input-margin-pn" />
</div>
<div class="form-group">
    <label for="radPNStartsWith">Starts With: </label>
    <input type="radio" id="radPNStartsWith" name="partNumber" checked  value="StartsWith"/>
</div>
<div class="form-group">
    <label for="radPNContains">Contains: </label>
    <input type="radio" id="radPNContains" name="partNumber" value="Contains" />
</div>
<div class="form-group">
    <label for="radPNExactMatch">Exact Match: </label>
    <input type="radio" id="radPNExactMatch" name="partNumber" value="ExactMatch" />
</div>

And my JavaScript is:

我的观点是:JavaScript

        alert($('input[name=partNumber]:checked', '#fsPartNum').val()); 
    if(txtPartNumber.val() !== ''){
        message = 'Customer Part Number';
    }
    else if(txtCommercialPartNumber.val() !== ''){

    }
    else if(txtDescription.val() !== ''){

    }

Just saying any containing tag with an ID can be used. For DNNers, this is good to know. The end goal here is pass to the mid-level code what is needed to start a parts search in SQL Server.

就是说任何包含ID的标签都可以使用。对于DNNers,这是很好的了解。这里的最终目标是将在SQL Server中启动部分搜索所需的内容传递给中级代码。

This way I don't have to copy the much more complicated previous C# code also. The heavy lifting is being done right here.

这样,我就不必复制更复杂的c#代码了。这里正在进行繁重的工作。

I had to look a bit for this and then tinker with it to get it to work. So for other DNNers, hopefully this is easy to find.

我得找点东西,然后修改一下才能让它工作。所以对于其他dnner,希望这个很容易找到。

#29


1  

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>