简体   繁体   English

使用jQuery捕获当前(不是之前)选定的单选按钮的值

[英]capture the value of the current (not previous) selected radio button with jQuery

I want to be able to get the value that I just selected when capturing the click of a radio button. 我希望能够获得在捕获单选按钮时刚刚选择的值。 The small snippet of code below returns the previous value, however if I click 'Male' then I want to capture it and then do something else with the gender var. 下面的小代码片段会返回之前的值,但是如果我单击“男性”,那么我想捕获它,然后使用gender var执行其他操作。

$(document).ready(function() {

     $('input[name=gender]').click(function() {
          var gender = $('input[name=gender]:checked').val(); 
     });

});

<input type="radio" name="gender" value="male" />Male 
<input type="radio" name="gender" value="female" />Female

This may appear like a minor question, and likely is, but I may be missing the wood from the trees because it is late in the day. 这可能看起来像一个小问题,可能是,但我可能会错过树木,因为它是在一天的晚些时候。

Use $(this).val() , It will give you the current radio button being clicked. 使用$(this).val() ,它会显示当前单击的单选按钮。 Your code is also working fine but you are using need less selector. 您的代码也正常工作,但您使用的需要更少的选择器。 Check demo of your code here 在这里查看您的代码的演示

Live Demo 现场演示

$(document).ready(function() {

     $('input[name=gender]').click(function() {
          var gender = $(this).val(); 
     });

});

try change event, this is better solution then click 尝试更改事件,这是更好的解决方案,然后单击

http://jsbin.com/arohuk/1/edit http://jsbin.com/arohuk/1/edit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM