首页 > 解决方案 > 使用 JQuery 更改单选按钮检查状态

问题描述

我有两个带有一个输入文本的单选按钮,当我插入大于 12 的值时,它会自动检查RadioBtn2,否则会检查RadioBtn1

它工作正常,但是当我返回文本框并再次更改值时,它无法正常工作,直到我刷新页面

$(function() {
  $('#field222').change(function() {
    var text_value = $("#field222").val();
    if (text_value >= '12') {
      $('input:radio[id="RadioBtn2"]').attr('checked', 'checked');
    } else {
      $('input:radio[id="RadioBtn1"]').attr('checked', 'checked');
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' class='input-lg' id='field222'>
<input type='radio' name='Radios' id='RadioBtn1' value='option1' checked>First
<input type='radio' name='Radios' id='RadioBtn2' value='option1' >Secend

标签: javascriptjqueryhtml

解决方案


那是因为您在 if 语句中的条件不正确。在进行大于检查之前,您需要将值解析为整数。

您还需要将更改事件更改为 keyup 并将属性检查设置为 true:

var text_value = parseInt($("#field222").val());
if (text_value >= 12) {
  $('input:radio[id="RadioBtn1"]').prop("checked", true);
} else {
  $('input:radio[id="RadioBtn2"]').prop("checked", true);
}

$(function() {
  $('#field222').keyup(function() {
    var text_value = parseInt($("#field222").val());
     debugger;
     if (text_value >= 12) {
       $('input:radio[id="RadioBtn1"]').prop("checked", true);
     } else {
       $('input:radio[id="RadioBtn2"]').prop("checked", true);
     }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' class='input-lg' id='field222'>
<input type='radio' name='Radios' id='RadioBtn1' value='option1' checked>First
<input type='radio' name='Radios' id='RadioBtn2' value='option1' checked>Secend


推荐阅读