javascript - 使用 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
解决方案
那是因为您在 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
推荐阅读
- oracle - 用触发器阻止数据库写入
- linux - 如何按点获取有向图
- ssh - 无法使用 ssh - 公钥问题
- android - 无法从像 www.exemple.com/json.php?apicall=cat 这样的 url 获取 json 数据
- ruby - 在 Ruby 中收集关键字参数
- html - 为什么我的代码脚本不执行这个 CSS 类?
- javascript - 如何删除出现在自动完成搜索字段中的文本“未定义”?
- twitter - 有没有办法使用媒体资源的 URL 将媒体上传到 Twitter API?
- android - 它不是在 Array List 中添加新项目,而是覆盖我的应用程序中的现有项目
- python - New column based on multiple conditions ignoring missing values