如何检查jquery选中了哪个单选按钮?

时间:2019-02-13 21:46:32

标签: jquery function

我试图根据选中的单选按钮来打印文本。 你能告诉我怎么了吗?

只需获取“错误”输出即可。

<input type="radio" name="feedback-form-visit-again" id="genderm" class="gendercheck" value="0" required> m
<input type="radio" name="feedback-form-visit-again" id="genderw" class="gendercheck" value="1"> w

<span class="gendertest">*Output*</span>
$(document).ready(function() {
  $(".gendercheck").change(function() {
    if (gender.value == 0) {
      $(".gendertest").text("m");
    } else if (gender.value == 1) {
      $(".gendertest").text("w");
    } else {
      $(".gendertest").text("error");
    }
  });
});

2 个答案:

答案 0 :(得分:1)

您只需要在代码中定义gender(因为您试图通过value访问gender的{​​{1}}属性)。

尝试类似的方法(我已经测试过并且可以正常工作):

gender.value

为了好玩,只想向您展示一个使用更少代码行的示例。基本上,打印单选输入的值,而不是定义if / else语句。 您需要修改html输入:

$(document).ready(function() {
  $('.gendercheck').change(function() {
    var selectedRadio = $('.gendercheck:checked'); // this is the "checked" radio button that has the class you're using. using .value would be more of the vanilla JS way, which isn't bad, but if you wanted to do it the jQuery way, just get the val like this --> selectedRadio.val(); 
    if (selectedRadio.val() == 0) {
      $('.gendertest').text('m');
    } else if (selectedRadio.val() == 1) {
      $('.gendertest').text('w');
    } else {
      $('.gendertest').text('error');
    }
  });
});
<input type="radio" name="feedback-form-visit-again" id="genderm" class="gendercheck" value="m" required> men
<input type="radio" name="feedback-form-visit-again" id="genderw" class="gendercheck" value="w"> women

答案 1 :(得分:0)

$(".gendercheck").on("change", function() {
  var selected_ID = ($(this).attr('id'));
  if (selected_ID == "genderm") {
    $(".gendertest").text("m");
  } else if (selected_ID == "genderw") {
    $(".gendertest").text("w");
  } else {
    $(".gendertest").text("error");
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="feedback-form-visit-again" id="genderm" class="gendercheck" value="0" required> m
<input type="radio" name="feedback-form-visit-again" id="genderw" class="gendercheck" value="1"> w
<br>
<span class="gendertest">*Output*</span>